I am new to golang, so appologize if this question is too naive. Looked around, but could not find answer to my basic question.
Lets say I have a concrete struct and methods as shown below.
type MyData struct{
field1 string
field2 int
}
func(a MyData) OperatorOnString() string{
return a.field1.(string)
}
func(a MyData) OperatorOnInt() int{
return a.field2.(int)
}
My question is, can I type cast and return rather than performing assertion? From what I have learned so far is that, assertion is used on data of type interface. But in this case I have concrete type. Should I still use assertion or I can do something like return int(a.field2)
. I know this example is trivial, but the point that I am confused is when to use between the two conversion types. Or is there some golang idiomaticity involved here?
Thanks
First of all, type assertion can be used only on interfaces:
For an expression
x
of interface type and a typeT
, the primary expression
x.(T)
asserts that
x
is not nil and that the value stored inx
is of typeT
. The notationx.(T)
is called a type assertion.
But you're applying it to non interface typed fields (int
and string
). That makes compiler unhappy.
Secondly, if you want to return type T
from a method/function, it's always enough to return an expression of type T
, which your fields already happen to be. The correct code is then easy:
package main
import "fmt"
type MyData struct {
field1 string
field2 int
}
func (a MyData) OperatorOnString() string {
return a.field1
}
func (a MyData) OperatorOnInt() int {
return a.field2
}
func main() {
a := MyData{"foo", 42}
fmt.Println(a.OperatorOnString(), a.OperatorOnInt())
}
Playground
Output:
foo 42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With