Nullifying an Interface in Golang
Problem:
Attempting to nullify an internal value of an interface raises the question: how to implement such a function, setNil(typ interface{})?
Answer:
To effectively nullify an interface, it's crucial to remember that working with a pointer value is different from working with an interface value. As pointers are passed by reference, a pointer to the interface must be passed to modify its internal state.
Function for Nullification of Interface{}:
<code class="go">func setNilIf(v *interface{}) { *v = nil }</code>
Usage:
<code class="go">var i interface{} = "Bob" fmt.Printf("Before: %v\n", i) setNilIf(&i) fmt.Printf("After: %v\n", i)</code>
Output:
Before: Bob After: <nil>
Function for Nullification of Pointers (Unsafe.Pointer):
To nullify a pointer, it can be converted to an unsafe.Pointer and dereferenced:
<code class="go">func setNilPtr(p unsafe.Pointer) { *(**int)(p) = nil }</code>
Usage:
<code class="go">typ := &TYP{InternalState: "filled"} fmt.Printf("Before: %v\n", typ) setNilPtr(unsafe.Pointer(&typ)) fmt.Printf("After: %v\n", typ)</code>
Output:
Before: &{filled} After: <nil>
Function for Nullification of Pointers (Reflection):
Finally, reflection can also be used to nullify a pointer:
<code class="go">func setNilPtr2(i interface{}) { v := reflect.ValueOf(i) v.Elem().Set(reflect.Zero(v.Elem().Type())) }</code>
Usage:
<code class="go">typ2 := &TYP{InternalState: "filled"} fmt.Printf("Before: %v\n", typ2) setNilPtr2(&typ2) fmt.Printf("After: %v\n", typ2)</code>
Output:
Before: &{filled} After: <nil>
However, for simplicity, it's recommended to directly assign nil to nullify a pointer:
<code class="go">i = nil typ = nil</code>
The above is the detailed content of How do you nullify an interface in Golang?. For more information, please follow other related articles on the PHP Chinese website!