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

Susan Sarandon
Release: 2024-10-31 10:08:02
Original
136 people have browsed it

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

Example:

<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

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

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

Output:

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

Using Reflection:

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

Example:

<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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!