Home > Backend Development > Golang > How to Correctly Initialize Embedded Structs in Go?

How to Correctly Initialize Embedded Structs in Go?

Patricia Arquette
Release: 2024-12-24 10:21:24
Original
580 people have browsed it

How to Correctly Initialize Embedded Structs in Go?

Golang Embedded Struct Types: Understanding the Syntax and Usage

When working with embedded struct types in Go, it's crucial to comprehend their syntax and proper usage. This article addresses the issue of being unable to initialize an embedded struct.

Problem:

Consider the following types:

type Value interface{}

type NamedValue struct {
    Name  string
    Value Value
}

type ErrorValue struct {
    NamedValue
    Error error
}
Copy after login

Attempting to initialize an ErrorValue using the syntax:

e := ErrorValue{Name: "alpha", Value: 123, Error: err}
Copy after login

results in an error.

Solution:

Embedded types, also known as unnamed fields, are referred to by their unqualified type name. In the provided code, the syntax for initializing the ErrorValue is incorrect.

As per the Go language specification, an embedded field should be initialized using the type name without a field name. Here's the correct syntax:

e := ErrorValue{NamedValue: NamedValue{Name: "fine", Value: 33}, Error: err}
Copy after login

Alternatively, you can omit the field names from the composite literal:

e := ErrorValue{NamedValue{"fine", 33}, err}
Copy after login

Example:

package main

import "fmt"

type Value interface{}

type NamedValue struct {
    Name  string
    Value Value
}

type ErrorValue struct {
    NamedValue
    Error error
}

func main() {
    e := ErrorValue{NamedValue{Name: "alpha", Value: 123}, fmt.Errorf("some error")}
    fmt.Println(e)
}
Copy after login

Output:

{NamedValue:{Name:alpha Value:123} Error:some error}
Copy after login

By understanding the syntax and usage of embedded struct types, you can effectively leverage them in your Go programs.

The above is the detailed content of How to Correctly Initialize Embedded Structs in Go?. 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