casting - Type cast vs type assertion on concrete struct? -
i new golang, appologize if question naive. looked around, not find answer basic question.
lets have concrete struct , methods 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 type cast , return rather performing assertion? have learned far that, assertion used on data of type interface. in case have concrete type. should still use assertion or can return int(a.field2). know example trivial, point confused when use between 2 conversion types. or there golang idiomaticity involved here?
thanks
first of all, type assertion can used on interfaces:
for expression
xof interface type , typet, primary expression
x.(t) asserts
xnot nil , value stored inxof typet. notationx.(t)called type assertion.
but you're applying non interface typed fields (int , string). makes compiler unhappy.
secondly, if want return type t method/function, it's enough return expression of type t, fields happen be. correct code 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() { := mydata{"foo", 42} fmt.println(a.operatoronstring(), a.operatoronint()) } output:
foo 42
Comments
Post a Comment