简体   繁体   中英

Type cast vs type assertion on concrete struct?

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 type T , the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T . The notation x.(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM