I am using this construct to simulate a set
type MyType uint8 map[MyType]interface{}
I then add in all my keys and map them to nil
.
I've learnt that it is also possible to use
map[MyType]struct{}
Any benefits of using the empty struct versus interface{}
.
Empty interfaces are used to mark the class, at run time type check can be performed using the interfaces. For example An application of marker interfaces from the Java programming language is the Serializable interface.
Often you don't need data on it, just methods with predefined input and output. Go has no Set object. Bit can be easily realized as a map[keyType]struct{} .
Empty Interface to Pass Function Argument of Any Type Normally in functions, when we pass values to the function parameters, we need to specify the data type of parameters in a function definition. In the above example, we have used an empty interface i as the parameter to the displayValue() function.
Memory usage. For example, types struct{}
, interface{}
, and bool
,
package main import ( "fmt" "unsafe" ) func main() { var s struct{} fmt.Println(unsafe.Sizeof(s)) var i interface{} fmt.Println(unsafe.Sizeof(i)) var b bool fmt.Println(unsafe.Sizeof(b)) }
Output (bytes for 32-bit architecture):
0 8 1
Output (bytes for 64-bit architecture):
0 16 1
References:
Go Data Structures: Interfaces
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With