I’m pretty new to Golang. I’m attempting to implement what, within the C, language can be a tagged union. I discovered some instance code on: Go and Algebraic Knowledge Varieties – Eli Bendersky’s web site
I believe I perceive the instance, and am attempting to emulate it in my code. Here’s a excerpt of my full program that will get an error that I don’t perceive. All of it appears okay to me.
bundle important
sort Obj interface {
isObj()
}
sort Tspecial struct {
subtype int
}
func (Tspecial) isObj() {}
func make_special(subtype int) *Obj {
n := Tspecial{subtype}
return &n
}
func important() {
// dot := make_special(1)
}
It will get the next error with go model 1.19.1:
./check.go:15:9: can’t use &n (worth of sort *Tspecial) as sort *Obj in return assertion:
*Tspecial doesn’t implement *Obj (sort *Obj is pointer to interface, not interface)
I believe I’ve issues such that Tspecial implement Obj, so why wouldn’t the handle of a Tspecial be a *Obj ?
In any case, can somebody please inform me my error. I’m positive there’s a technique to do what I’m attempting to do.
bundle important
import "fmt"
sort Obj interface {
isObj()
}
sort Tspecial struct {
subtype int
}
func (ts *Tspecial) isObj() {}
func make_special(subtype int) Obj {
n := Tspecial{subtype}
return &n
}
func important() {
dot := make_special(1)
fmt.Println(dot)
}
Properly, your suggestion compiles, bt I can’t perceive why it does. It appears very fallacious to me, as a result of the perform make_special says it returns an Obj, not some extent to an Obj, and your code returns “&n”, the handle of n, which needs to be a pointer to an Obj.
Can somebody please clarify, slowly, or level me to documentation, and assist me perceive this. I should be lacking one thing elementary.
Please verify this model first:
bundle important
import (
"fmt"
"replicate"
)
sort Obj interface {
isObj()
}
sort Tspecial struct {
subtype int
}
func (t Tspecial) isObj() {
fmt.Println("Implementation of isObj in Tspecial")
}
func make_special(subtype int) Obj {
n := Tspecial{subtype}
n.isObj()
fmt.Println(replicate.TypeOf(n))
return n
}
func important() {
dot := make_special(1)
fmt.Println(dot)
fmt.Println(replicate.TypeOf(dot))
}
It prints :
isObj:Tspecial implementation
TypeOf(n)= important.Tspecial
dot= {1}
TypeOf(dot)= important.Tspecial
Successfully Tspecial is taken into account as Obj as a result of it implements all of the required funcionality of that interface.
The issue is with pointers. One factor is a pointer to Tspecial and anoter factor is a pointer to Obj.
To return a *Obj from make_special ypou have to create a temp object of that sort and solid “n” to that after which return his pointer.
It’s one thing like:
func make_special(subtype int) *Obj {
n := Tspecial{subtype}
n.isObj()
fmt.Println(replicate.TypeOf(n))
o := Obj(n)
return &o
}
HTH,
Yamil