简体   繁体   中英

struct initialization: too few values in p.U literal or implicit assignment of unexported field 'c' in p.U literal?

I am sorry for that simple question I have the following code

// package p
package p
// U type 
type U struct {
    A, B int
    c    int
} // A and B are exported only
// main
package main

import (
    "fmt"
    "./p"
)

func main() {
    pp := p.U{A: 3, B: 4}
    uu := p.U{3, 5}    // the error resulted from this line
    fmt.Println(pp)
    fmt.Println(uu)
}

when I try to compile I get an error: too few values in pU literal . I'm expecting that there no need to add c value. when I try to add the c value I get another expected error: implicit assignment of unexported field 'c' in pU literal

You must keep the following rules in mind while creating a struct literal:

  1. A key must be a field name declared in the struct type.
  2. An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
  3. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
  4. A literal may omit the element list; such a literal evaluates to the zero value for its type.
  5. It is an error to specify an element for a non-exported field of a struct belonging to a different package.

In golang, there's to ways to instantiate structs: with keys and without keys.

When instantiating with keys, you would write the value of each field name next to the field name like such:


type Employee struct {

name string
age int
boss bool

}

employee := Employee{name: "John", age: 30}

When instantiating without keys, you just write the value of each field without writing the field names like such:

type Employee struct{

name string
age int
boss bool

}

employee := Employee{"John", 30, false}

As you might've noticed, when instantiating with keys, you don't have to specify a value for each field (you don't have to include a value for boss). This is because, since you're only giving values to specific fields, golang can assume the values for the other fields.

On the other hand, when instantiating without keys, you do have to specify a value for each field since, otherwise, if you didn't specify a value for each field, golang would not be able to assume which value goes to which field.

So, long story short, you can only instantiate structs without keys if you specify values for each field. Otherwise, you have to use keys and allow golang to assume the default values for the other fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM