Created
February 8, 2022 02:56
Star
You must be signed in to star a gist
Nilling interface values but not types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"unsafe" | |
"github.com/AlekSi/pointer" | |
) | |
// interface defs from reflect library | |
type tflag uint8 | |
type nameOff int32 // offset to a name | |
type typeOff int32 // offset to an *rtype | |
type rtype struct { | |
size uintptr | |
ptrdata uintptr // number of bytes in the type that can contain pointers | |
hash uint32 // hash of type; avoids computation in hash tables | |
tflag tflag // extra type information flags | |
align uint8 // alignment of variable with this type | |
fieldAlign uint8 // alignment of struct field with this type | |
kind uint8 // enumeration for C | |
// function for comparing objects of this type | |
// (ptr to object A, ptr to object B) -> ==? | |
equal func(unsafe.Pointer, unsafe.Pointer) bool | |
gcdata *byte // garbage collection data | |
str nameOff // string form | |
ptrToThis typeOff // type for pointer to this type, may be zero | |
} | |
// emptyInterface is the header for an interface{} value. | |
type emptyInterface struct { | |
typ *rtype | |
word unsafe.Pointer | |
} | |
func NullInterfaceValue(x []interface{}) { | |
for i := range x { | |
e := (*emptyInterface)(unsafe.Pointer(&x[i])) | |
e.word = nil | |
/* | |
fmt.Printf("%+v", *e.typ) | |
fmt.Println("Val: ", x, "x == nil? ", x == nil) | |
*/ | |
} | |
} | |
func main() { | |
ifaces := []interface{}{ | |
new(int), | |
new(string), | |
new(T), | |
} | |
ifaces[0] = pointer.ToInt(4) | |
ifaces[1] = pointer.ToString("xyz") | |
ifaces[2] = &T{Name: "James"} | |
fmt.Printf("Before =====") | |
printArr(ifaces) | |
NullInterfaceValue(ifaces) | |
fmt.Printf("\n\nAfter ======") | |
printArr(ifaces) | |
} | |
func printArr(ifaces []interface{}) { | |
for i, v := range ifaces { | |
fmt.Println("element", i) | |
fmt.Println(" value: ", v) | |
fmt.Println(" element == nil?", v == nil) | |
} | |
} | |
type T struct { | |
Name string | |
} | |
func (t *T) Nom() string { | |
return t.Name | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment