Image for post
Image for post
https://en.wikipedia.org/wiki/Psycho_(1960_film)

Type assertions in Go

Michał Łowicki
Sep 7, 2016 · 3 min read
PrimaryExpression.(Type)
type I interface {
walk()
quack()
}
type S struct{}func (s S) walk() {}
func (s S) quack() {}
var i I
i = S{}
fmt.Println(i.(interface {
walk()
}))
type I interface {
walk()
quack()
}
type S struct{}
S{}.(I) // invalid type assertion: S literal.(I) (non-interface type S on left)
type I interface {
walk()
}
type A struct{}func (a A) walk() {}type B struct{}func (b B) walk() {}func main() {
var i I
i = A{} // dynamic type of i is A
fmt.Printf(“%T\n”, i.(A))
i = B{} // dynamic type of i is B
fmt.Printf(“%T\n”, i.(B))
}
type I interface {
walk()
}
type J interface {
quack()
}
type K interface {
bark()
}
type S struct{}func (s S) walk() {}func (s S) quack() {}func main() {
var i I
i = S{}
fmt.Printf(“%T\n”, i.(J))
fmt.Printf(“%T\n”, i.(K)) // panic: interface conversion: main.S is not main.K: missing method bark
}
type I interface {
walk()
}
type A struct{}func (a A) walk() {}type B struct{}func (b B) walk() {}func main() {
var i I
i = A{}
fmt.Printf(“%T\n”, i.(A))
fmt.Printf(“%T\n”, i.(B)) // panic: interface conversion: main.I is main.A, not main.B
}
type C struct{}
fmt.Printf(“%T\n”, i.(C))
impossible type assertion:
C does not implement I (missing walk method)
type I interface {
walk()
}
type A struct {
name string
}
func (a A) walk() {}type B struct {
name string
}
func (b B) walk() {}func main() {
var i I
i = A{name: “foo”}
valA, okA := i.(A)
fmt.Printf("%#v %#v\n", valA, okA)
valB, okB := i.(B)
fmt.Printf("%#v %#v\n", valB, okB)
}
main.A{name:"foo"} true
main.B{name:””} false

golangspec

A series dedicated to deeply understand Go’s specification…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store