GoSuda

Any is not Any, but Any is Any

By snowmerak views ...

Any

In the Go language, the any type is an alias for interface{}, a magical interface capable of holding values of every type. In other words, a variable of type any can be assigned a value of any type.

1var a any
2a = 42          // int
3a = "hello"     // string
4a = true        // bool
5a = 3.14        // float64

In this way, the any type can hold values of various types, allowing you to write flexible code. However, there are several points to be careful about when using the any type.

Type Assertion

To use the actual value held in an any type variable, you must use a type assertion. A type assertion serves to inform the compiler that an any type variable is of a specific type.

1var a any = "hello"
2str, ok := a.(string)
3if ok {
4    fmt.Println("String value:", str)
5} else {
6    fmt.Println("Not a string")
7}

In the example above, a.(string) asserts that a is of type string. If a is not of type string, ok becomes false, which prevents the program from panicking.

Type Switch

A type switch allows you to perform different actions depending on the actual type of an any type variable. This is useful when you need to handle multiple types.

 1var a any = 42
 2switch v := a.(type) {
 3case int:
 4    fmt.Println("Integer:", v)
 5case string:
 6    fmt.Println("String:", v)
 7case bool:
 8    fmt.Println("Boolean:", v)
 9default:
10    fmt.Println("Unknown type")
11}

In the example above, a.(type) inspects the actual type of a and executes the case that matches that type.

Reflection

Using the reflect package in Go, you can dynamically inspect and manipulate the type and value of an any type variable at runtime. This is useful when working with complex data structures.

1import (
2    "fmt"
3    "reflect"
4)
5
6var a any = 3.14
7v := reflect.ValueOf(a)
8fmt.Println("Type:", v.Type())
9fmt.Println("Value:", v.Float())

In the example above, the reflect package is used to check the type and value of a at runtime.

EFace

In the Go language, interfaces are divided into two main forms: EFace (Empty Interface) and IFace (Interface with Methods). Of these, EFace is the same concept as the any type we have covered so far.

Structure

Since EFace is a special structure that exists only within the Go runtime, we will work with a mimic here.

 1type runtimeTypeMimic struct {
 2	Size_       uintptr
 3	PtrBytes    uintptr // number of (prefix) bytes in the type that can contain pointers
 4	Hash        uint32  // hash of type; avoids computation in hash tables
 5	TFlag       uint8   // extra type information flags
 6	Align_      uint8   // alignment of variable with this type
 7	FieldAlign_ uint8   // alignment of struct field with this type
 8	Kind_       uint8   // enumeration for C
 9	Equal       func(unsafe.Pointer, unsafe.Pointer) bool
10	GCData      *byte
11	Str         int32 // string form
12	PtrToThis   int32 // type for pointer to this type, may be zero
13}
14
15type eFaceMimic struct {
16	Type *runtimeTypeMimic
17	Data unsafe.Pointer
18}

EFace has two fields:

  • Type: A pointer that holds metadata about the actual type of the value.
  • Data: A pointer that holds the actual value.

Additionally, EFace internally manages type information through the runtimeType structure. This structure contains various metadata, such as the size, alignment, and hash value of the type.

Within this, the parts we should pay attention to are the Kind_, Hash, and Equal fields. Kind_ indicates the kind of the type, while Hash and Equal are used to compare types and compute hash values in hash tables.

Wrapping

Now, let's wrap this EFace so that we can use black magic more conveniently.

 1type TypeInfo struct {
 2	Hash  uint32
 3	TFlag uint8
 4	Kind  uint8
 5	Equal func(unsafe.Pointer, unsafe.Pointer) bool
 6	This  unsafe.Pointer
 7}
 8
 9func GetTypeInfo(v any) TypeInfo {
10	eface := *(*eFaceMimic)(unsafe.Pointer(&v))
11	return TypeInfo{
12		Hash:  eface.Type.Hash,
13		TFlag: eface.Type.TFlag,
14		Kind:  eface.Type.Kind_,
15		Equal: eface.Type.Equal,
16		This:  eface.Data,
17	}
18}

The above function takes an any type variable, extracts the internal EFace structure, retrieves the type information from it, and returns it as a TypeInfo structure. Now you can easily access the type's hash value, kind, comparison function, and so on using this TypeInfo.

Usage

Usage is really simple. You just pass an any type variable to the GetTypeInfo function.

 1func main() {
 2	i := 42
 3	eface := GetTypeInfo(i)
 4	fmt.Printf("%+v\n", eface)
 5
 6	f := 3.14
 7	eface2 := GetTypeInfo(f)
 8	fmt.Printf("%+v\n", eface2)
 9
10	// Compare the two values using the Equal function from the type info
11	log.Println(eface.Equal(eface.This, eface.This))
12	log.Println(eface2.Equal(eface2.This, eface2.This))
13	log.Println(eface2.Equal(eface.This, eface2.This))
14	log.Println(eface.Equal(eface2.This, eface.This))
15}

In the example above, integer and floating-point values are passed to the GetTypeInfo function to print their respective type information, and the Equal function is used to compare the values. Through this, you can obtain type information and compare types more quickly.

In addition, this approach can be used identically for structs, pointers, interfaces, and so on, and it can also resolve the typed nil problem, a fairly common issue. Hash will be assigned if a type exists, whereas This is 0 if it is nil.

Conclusion

EFace plays an important role in handling the any type in the current Go language. Through it, values of various types can be processed flexibly and quickly, and type information can be obtained and utilized in detail. However, since this is a feature hidden within the runtime, it may be affected by changes to the language specification, so caution is required.