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:
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.