Home > Backend Development > Golang > How to Initialize a String Pointer in a Go Struct?

How to Initialize a String Pointer in a Go Struct?

Linda Hamilton
Release: 2024-11-14 16:00:03
Original
972 people have browsed it

How to Initialize a String Pointer in a Go Struct?

Initializing a String Pointer in a Go Struct

In Go, structs can contain pointers to other values, including strings. While it's straightforward to initialize strings directly in structs, initializing string pointers can present a challenge.

Problem

When attempting to initialize a struct with a string pointer (*string) as a default value, an error occurs:

cannot use "string" (type string) as type *string in field value
Copy after login

Solution

To initialize a string pointer in a struct, you can't directly assign a constant string value to it. Instead, create a variable, assign the value to it, and then pass the variable's address to the string pointer:

type Config struct {
  Uri       *string
}

func init() {
  v := "my:default"
  var config = Config{ Uri: &v }
}
Copy after login

By using the & operator, you obtain the address of the variable (&v), which can then be assigned to the string pointer. This enables the comparison of two struct instances where Uri can be nil if not set.

The above is the detailed content of How to Initialize a String Pointer in a Go Struct?. 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