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 x of interface type , type t, primary expression

x.(t) 

asserts x not nil , value stored in x of type t. notation x.(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()) } 

playground


output:

foo 42 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -