Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference in using an empty interface or an empty struct as a map's value?

Tags:

go

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{}.

like image 213
canadadry Avatar asked Mar 31 '14 19:03

canadadry


People also ask

Why would you use an empty 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.

Why do we tend to use empty struct in Golang?

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{} .

How do you pass an empty interface?

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.


1 Answers

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

like image 78
peterSO Avatar answered Sep 18 '22 14:09

peterSO