Search code examples
pointersgotype-assertion

golang type assertion, what the different between interface{}(pointer) and interface{}(object)?


Why do I assign a value to a type assertion result where the interface is assigned by a pointer, and it comes to a "cannot assign" error when I do it to a interface which is assigned by a struct object?

Here's my code:

package main

import (
    "fmt"
)

type Person interface {
    SayHi()
}

type Student struct {
    id int
    name string
}

func (s Student) SayHi() {
    fmt.Println("hi, i am", s.name, " my id is:", s.id)
}

func main() {
    p1 := Person(&Student{id: 123, name: "William"})
    p1.SayHi()      // ok
    p1.(*Student).SayHi()  // ok here
    p1.(*Student).id = 456 // ok here
    p2 := Person(Student{id: 123, name: "William"})
    p2.SayHi()         //ok 
    p2.(Student).SayHi()  // ok here
    p2.(Student).id = 456 // error here and why?
    fmt.Println("p1:", p1, " p2:", p2)
}

https://play.golang.org/p/dwkvLzng_n


Solution

  • the result of value.(typeName) is a new (copy) value with the static type typeName.

    p2.(Student).id=456 will create a temporary Student value, any modifications of that value would be discarded. So the language just disallows this mistake.