Golang pointer of type within a struct

Issue

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

type Testing struct {
    firstname string
}

type Another struct {
    *Testing
}

func main() {
    var f = Another{firstname: "sasdf"}
    fmt.Println(f)
}

Here I’ve used a pointer in the struct. Its something i’ve seen used in repository. But i’m not understanding.

What does this do? First i expected it would extend the properties of Testing struct. This ins’t true.

From my inspected the Another struct may have a Testing property that holds a value. Giving it var f = Another{Testing: &Testing{firstname: "afsdf"}} and printing yields a struct containing a memory address. Do this syntax is a new struct with a property that contains a pointer to a object of T named the name of the type

Solution

From the spec:

A field declared with a type but no explicit field name is called an embedded field.

A field or method f of an embedded field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.
Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

The last quoted sentence is why the composite literal Another{firstname: "sasdf"} did not work.

Answered By – Adrian

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.