Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, April 25, 2022

Update Go's Empty Interface

 

Some functions in Go need to update an empty interface, while finding out the actual type of data that should be used in some way. In this post we will examine how to set value for the Go's empty interface.

Let's start by configuring two structs:


import (
"fmt"
"reflect"
)

type Data1 struct {
name string
}

type Data2 struct {
age int
}



Next we use Go's reflect to update an empty interface:



func initialize(kind string, data interface{}) {
dataValue := reflect.ValueOf(data)

var setValue reflect.Value
if kind == "data1" {
initialValue := Data1{name: "init"}
setValue = reflect.ValueOf(initialValue)
} else {
initialValue := Data2{age: 120}
setValue = reflect.ValueOf(initialValue)
}
dataValue.Elem().Set(setValue)
}



Now we can send any type of struct to the function, and it will try to set its value, for example:



data1 := Data1{}
initialize("data1", &data1)
fmt.Printf("%+v\n", data1)


This will print:


{name:init}


We can do the same for the second type of struct:



data2 := Data2{}
initialize("data2", &data2)
fmt.Printf("%+v\n", data2)


And this time we get the following:


{age:120}



If we send a wrong type of structure, we will have a Go panic error, for example:


initialize("data2", &data1)

Will panic with the following error:



panic: reflect.Set: value of type main.Data2 is not assignable to type main.Data1




No comments:

Post a Comment