GO的struct與C的struct區別
1、struct的宣告
GO中:
type student struct {
Name string
Age int
}
C中
#include <stdio.h>
typedef struct Student{
int Age;
char Name[20];
}struct_int;
int main()
{
struct_int a ={1,"Tom"};
struct Student b = {2,"Faker"};
printf("%d,%s\n",a.Age,a.Name);
printf("%d,%s\n" ,b.Age,b.Name);
return 0;
}
首先:go語言中struct宣告時候是反過來的type student struct,通常是用student這個型別去宣告定義 如:var studetn_struct student
不可以像c語言在末尾直接寫struct_int
typedef struct Student{
int Age;
char Name[20];
}struct_int;
c語言中:一般是用struct_int去宣告結構體,或者直接加到typedef struct {}之後或者 struct Student(struct是不可以缺少的)。
2、初始化:
c中:struct_int a ={1,”Tom”,{1,”gogoing”}};有結構體嵌入的時候直接{}寫內容就可以了。
go:這樣是不行的。 a := person{{1}, “Tom”, 13}編譯會出現錯誤;正確寫法如下:
package main
import (
"fmt"
)
type human struct {
sex int
}
type person struct {
human
name string
age int
//sex int
}
func main() {
//var a person,
b := human{1}
//a := person{{1}, "Tom", 13}
//b = {sex::1}
a := person{human: struct{ sex int }{1}, name: "name", age: 2}
//a := human{1}
fmt.Println(a)
fmt.Println(b)
}
不過通常也不會用到以上寫法。
通常’.’引用結構體中的變數。
3、定義
c語言中:引用結構體指標的時候需要->就是(*p)
#include <stdio.h>
typedef struct human{
int sex;
char a[20];
};
typedef struct Student{
int Age;
char Name[20];
struct human human_stuct;
}struct_int;
int main()
{
struct_int a ={1,"Tom",{1,"gogoing"}};
struct Student b = {2,"Faker"};
struct Student *c = (struct Student *)malloc (sizeof(struct Student));
//char d[20] = "aaa";
c->Age= 1;
strcpy(c->Name,"aa");
printf("%d,%s,%s\n",a.Age,a.Name,a.human_stuct.a);
printf("%d,%s\n",b.Age,b.Name);
printf("%d,%s\n",c->Age,c->Name);
return 0;
}
而GO語言就簡單多了。‘.’是通用的。
c := &a,fmt.Println(c.age)。指標可以直接用’.’引用。最強大的是c是person結構體,person結構體中有human結構體,c可以直接引用human結構體中的成員fmt.Println(c.sex)。c語言是不行的。
在對char a[20];進行賦值的時候發現複製時候出現錯誤。那是c語言中如果陣列在宣告時沒有經行初始化,必須用strcpy等函式進行復制。
本來想對go進行測試,但是我輸入字串時候,提示字串是string型別。c語言中只要涉及指標都要對它進行初始化,沒有初始化,沒有申請空間會造成程式崩潰,是非常嚴重的錯誤。
c在對字串處理上是比較麻煩的,c++,go由於有string型別,處理一般不會造成程式崩潰。
go語言宣告和初始化是一起的,var預設初始化。b int,在程式中是不被允許的,這樣可以減少很多的錯誤。