简体   繁体   中英

too few values in struct initializer when initialize C struct in golang

I have tried the following program, but it told me "too few values in struct initializer" when compiling it.

package main

/*
#include <stdlib.h>
struct Person {
    char *name;
    int age;
    int height;
    int weight;
};
*/
import "C"
import "fmt"

type p C.struct_Person

func main() {

    person := p{C.CString("Giorgis"), 30, 6, 175}
    fmt.Println(person)
    fmt.Println(C.GoString(person.name))
    fmt.Println(person.age)
    fmt.Println(person.height)
    fmt.Println(person.weight)
}

How can I fix this wired problem? Additionally, when I changed type "char*" to "char", and the initializer. It works well.

struct Person {
    char name;
    int age;
    int height;
    int weight;
};

Also, when I use

struct Person {
    char *name;
};

it works well too.

Anyway, how can I fix it? Thanks.

Please try to put the field names in your struct literal.

person := p{name: C.CString("Giorgis"), age: 30, height: 6, weight: 175}

This is because an anonymous 4-byte padding field gets inserted between name and age.

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