Reputation: 3158
package main
import "fmt"
type Number int
func (n *Number) IncreaseMe(i int) {
*n += i
}
func main() {
n := Number(10)
n.IncreaseMe(90) // n is now supposed to be 100
fmt.Println(n)
}
When running the code above, it gives me the error message
invalid operation: *n += i (mismatched types Number and int)
Which is to be expected as it's trying to do a math operation on variables which don't share the same type.
I then tried
*n.(int) += i
which tells the compiler not to worry as *n can be safely treated as an integer, which leads me to
invalid type assertion: n.(int) (non-interface type *Number on left)
I believe this is happening because type assertions works only with interfaces, not custom types.
So what is the solution for this?
Upvotes: 2
Views: 3314
Reputation: 1323203
As mentioned in "Go: Named type assertions and conversions"
Type assertion works for interfaces only. Interface can have arbitrary underlying type, so we have type assertion and type switch to the rescue.
You don't need type assertion: you can just:
*n
to an int
: int(*n)
(since you know full well the actual type).convert back to Number
*n = Number(int(*n) + i)
See this play.golang.org: the output is 100.
As ruakh mentions in the comments:
Go splits the concept of "casting" into two separate concepts:
- one ("type conversions") for conversions that the compiler knows are correct, and
- one ("type assertions") for conversions that must be checked at runtime.
The latter only applies to interfaces, since only interfaces have additional type information at runtime that that's not known at compile time.
Upvotes: 5