Cast vs type assertion on concrete structure?

I am new to the Golang, so I apologize if this question is too naive. I looked around, but could not find the answer to my main question.

Suppose I have a specific structure 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 and return, and not fulfill the statement? From what I have learned so far, this statement is used for type interface data. But in this case, I have a specific type. Should I use a statement, or can I do something like return int(a.field2) . I know this example is trivial, but the point that I confused is when to use between two types of conversions. Or is there some kind of golian idiom here?

thanks

+6
source share
1 answer

First of all, type assertion can only be used on interfaces:

For an expression x type interface and type T main expression

 x.(T) 

claims that x not nil and that the value stored in x is of type T The notation x.(T) is called a type statement.

But you apply it for fields with non-interface ( int and string ). This makes the compiler unhappy .

Secondly, if you want to return type T from a method / function, it is always enough to return an expression of type T , which is already in your fields. The correct code is 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 
+9
source

Source: https://habr.com/ru/post/944527/


All Articles