Say I have something like this:
type Foo struct{
Bar string
}
func Exported (v interface{}){
// cast v to Foo
}
is there a way to cast v to Foo in the Exported func?
I tried a type assertion like so:
func Exported (v interface{}){
v, ok := v.(Foo)
if !ok {
log.Fatal("oh fuk")
}
// but v.Bar is not available here tho ??
}
The problem is that if I try to access v.Bar after the assertion, it doesn't compile.
func main() {
f := Foo{"test"}
Exported(f)
}
type Foo struct{
Bar string
}
func Exported (v interface{}){
t, ok := v.(Foo)
if !ok {
log.Fatal("boom")
}
fmt.Println(t.Bar)
}
I was making this mistake:
func Exported (v interface{}){
v, ok := v.(Foo)
if !ok {
log.Fatal("oh fuk")
}
// but v.Bar is not available here tho ??
}
you need to use a different variable name:
func Exported (x interface{}){
v, ok := x.(Foo)
if !ok {
log.Fatal("oh fuk")
}
// now v.Bar compiles without any further work
}
The problem is with the variable name v
. Please refer below code
func Exported (v interface{}){
v, ok := v.(Foo)
if !ok {
log.Fatal("oh fuk")
}
// but v.Bar is not available here tho ??
}
here, interface name is v
and after typecasting, it is assigning to variable v
Since v
is interface
type, you are not able to retrieve value of Foo
struct.
To overcome this problem, use another name in typecasting like
b, ok := v.(Foo)
And you will be able to get Bar
value using b.Bar
The working example is below:
package main
import (
"log"
"fmt"
)
func main() {
foo := Foo{Bar: "Test@123"}
Exported(foo)
}
type Foo struct{
Bar string
}
func Exported (v interface{}){
// cast v to Foo
b, ok := v.(Foo)
if !ok {
log.Fatal("oh fuk")
}
fmt.Println(b.Bar)
}