Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cast vs type assertion on concrete struct?

Tags:

casting

go

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

like image 510
Minty Avatar asked May 08 '13 13:05

Minty


1 Answers

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
like image 133
zzzz Avatar answered Sep 30 '22 18:09

zzzz