How Do I Access Embedded Fields in Go Structs?

Linda Hamilton
Release: 2024-10-27 13:38:29
Original
845 people have browsed it

How Do I Access Embedded Fields in Go Structs?

Accessing Struct Type Embedded Fields

In Go, struct types can contain embedded fields, which allow for embedding one or more types within a struct. This powerful feature enables code reuse and efficient memory management. However, understanding how to access these fields can be challenging while learning about pointers.

Consider the following struct definitions:

<code class="go">type Engine struct {
    power int
}

type Tires struct {
    number int
}

type Cars struct {
    *Engine // Embedded field with pointer
    Tires   // Embedded field without pointer
}</code>
Copy after login

As you've observed, within the Cars struct, an embedded type pointer *Engine is defined. This allows access to the Engine type's methods and fields via the Cars struct.

To access the power field of the Engine embedded field, you must first initialize both the Engine and Cars structs. In the main function:

<code class="go">func main() {
    car := new(Cars) // Initialize Cars struct
    car.Engine = new(Engine) // Initialize Engine struct explicitly
    car.power = 342 // Set power field
    car.number = 4 // Set number field
}</code>
Copy after login

By explicitly initializing both structs, you establish a connection between the embedded *Engine pointer and the actual Engine object. Now, you can access the power field through the Cars struct:

<code class="go">fmt.Println(car.power) // Prints 342</code>
Copy after login

Similarly, for the non-pointer embedded field Tires, you can directly access its number field:

<code class="go">fmt.Println(car.number) // Prints 4</code>
Copy after login

This example demonstrates how to properly initialize and access embedded fields within a struct, enabling you to fully utilize code reuse and efficient memory management.

The above is the detailed content of How Do I Access Embedded Fields in Go Structs?. 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!