Golang报错mixture of field:value and value initializers

时间:2023-03-10 06:31:32
Golang报错mixture of field:value and value initializers

Golang 在使用匿名成员初始化时,如果出现

mixture of field:value and value initializers

是因为初始化的方式不对,见代码:
package main

import (
"fmt"
) type Person struct {
Name string
Age int
Sex string
} type Student struct {
Person
Id string
Grade string
} func main() {
s1 := Student{Person: Person{Name: "张三", Age: , Sex: "男"}, Id: "", Grade: "三年级"}
fmt.Printf("%+v\n", s1) s2 := Student{Person{"张三", , "男"}, "", "三年级"}
fmt.Println(s2) s3 := Student{Person{Name: "张三", Age: , Sex: "男"}, Id: "", Grade: "三年级"} //报错 mixture of field:value and value initializers(字段的混合:值和值初始化器)
fmt.Println(s3)
}

s3直接导致代码编译不过去,想要指定字段就必须按 s1的方式 Person:Person{xxx:"xxx"},要么就不指定按照s2的方式