Created
June 8, 2021 16:00
-
-
Save Integralist/3097838786e069c33afe668ae767a367 to your computer and use it in GitHub Desktop.
[go type asserting/coercing] #go #golang #type #assert #coerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
bar and baz are structs with pointer reference to a foo struct. | |
there's a fooer interface for the foo struct | |
we also have a function that accepts a fooer | |
the purpose of the function is to coerce the arg from an interface type to a concrete type | |
*/ | |
package main | |
import ( | |
"fmt" | |
) | |
type foo struct { | |
msg string | |
enabled bool | |
} | |
func (f *foo) do(thing string) (string, error) { | |
return fmt.Sprintf("done %s -- %s", thing, f.msg), nil | |
} | |
type fooer interface { | |
do(thing string) (string, error) | |
} | |
type bar struct { | |
thing *foo | |
} | |
type baz struct { | |
thing *foo | |
} | |
func assignMsg(f fooer) { | |
if foothing, ok := f.(*foo); ok { | |
foothing.msg = "assigned dynamically" | |
} | |
fmt.Println(f.do("something here")) | |
} | |
func main() { | |
br := bar{thing: &foo{enabled: true}} | |
bz := baz{thing: &foo{enabled: true}} | |
fmt.Printf("br: %+v\n", br) | |
fmt.Printf("bz: %+v\n", bz) | |
ret, _ := br.thing.do("with bar") | |
fmt.Println(ret) | |
ret, _ = bz.thing.do("with baz") | |
fmt.Println(ret) | |
assignMsg(br.thing) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment