Home  >  Article  >  Backend Development  >  How to Set an Interface to Nil in Golang: What\'s the Difference Between Nil a Pointer and an Interface?

How to Set an Interface to Nil in Golang: What\'s the Difference Between Nil a Pointer and an Interface?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 10:08:02137browse

How to Set an Interface to Nil in Golang: What's the Difference Between Nil a Pointer and an Interface?

Setting an Interface to Nil in Golang

In Golang, an interface value represents an object's behavior, but it's not the actual object itself. When attempting to nil an internal value of an interface, you're actually dealing with a pointer to a concrete type, which differs from an interface value.

Nil an Interface

If you have an interface whose value you want to set to nil, use the following function:

<code class="go">func setNilIf(v *interface{}) {
    *v = nil
}</code>

Example:

<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>

Nil a Pointer

In your case, you're dealing with a pointer to a concrete type. To nil a pointer, you can use:

Using Unsafe.Pointer:

<code class="go">func setNilPtr(p unsafe.Pointer) {
    *(**int)(p) = nil
}</code>

Example:

<code class="go">type TYP struct {
    InternalState string
}
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>

Using Reflection:

<code class="go">func setNilPtr2(i interface{}) {
    v := reflect.ValueOf(i)
    v.Elem().Set(reflect.Zero(v.Elem().Type()))
}</code>

Example:

<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>

Note:

For simplicity, it's generally recommended to directly assign nil to the pointer variable, rather than using complex methods like those above.

The above is the detailed content of How to Set an Interface to Nil in Golang: What\'s the Difference Between Nil a Pointer and an Interface?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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