Home > Backend Development > Golang > How do you nullify an interface in Golang?

How do you nullify an interface in Golang?

Susan Sarandon
Release: 2024-11-01 21:11:02
Original
369 people have browsed it

How do you nullify an interface in Golang?

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>
Copy after login

Usage:

<code class="go">var i interface{} = "Bob"
fmt.Printf("Before: %v\n", i)
setNilIf(&i)
fmt.Printf("After: %v\n", i)</code>
Copy after login

Output:

Before: Bob
After: <nil>
Copy after login

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>
Copy after login

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>
Copy after login

Output:

Before: &{filled}
After: <nil>
Copy after login
Copy after login

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>
Copy after login

Usage:

<code class="go">typ2 := &TYP{InternalState: "filled"}
fmt.Printf("Before: %v\n", typ2)
setNilPtr2(&typ2)
fmt.Printf("After: %v\n", typ2)</code>
Copy after login

Output:

Before: &{filled}
After: <nil>
Copy after login
Copy after login

However, for simplicity, it's recommended to directly assign nil to nullify a pointer:

<code class="go">i = nil
typ = nil</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template