Home >Backend Development >Golang >What is the Go Equivalent of a C Void Pointer?

What is the Go Equivalent of a C Void Pointer?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 09:40:11290browse

What is the Go Equivalent of a C Void Pointer?

Go Equivalent of a Void Pointer in C

In Go, the concept of a void pointer in C is replaced by the empty interface, denoted as interface{}. This interface represents the set of all (non-interface) types. It allows you to store any type of value without having to specify the specific type.

To use the empty interface, simply declare a variable of type interface{}:

var value interface{}

This variable can then hold any value of any type:

value = 42
value = "Hello, world!"
value = struct{ name string }{name: "John"}

You can access the value stored in an empty interface using type assertions:

if x, ok := value.(int); ok {
    // x is an int
} else if y, ok := value.(string); ok {
    // y is a string
}

Update (2023-09-27):

Starting in Go 1.18, the any type is introduced as an alias for interface{}. It provides the same functionality as the empty interface, but it is more concise and easier to read.

var value any

value = 42
value = "Hello, world!"
value = struct{ name string }{name: "John"}

The above is the detailed content of What is the Go Equivalent of a C Void Pointer?. 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