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
Release: 2024-12-21 09:40:11
Original
223 people have browsed it

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

This variable can then hold any value of any type:

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

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

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

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!

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