结构体适用于需要将不同类型的数据放到一个对象中,比如定义一个人的信息,需要将这个人的姓名,排名,年龄等信息定义到一个数据类型当中。
c/c++的写法
void structDemo() {
//定义结构体
struct PersonInfo {
int index;
char name[30];
int age;
};
struct PersonInfo pInfo; //初始化一个pInfo的结构体变量
pInfo.index = 0; //为结构体变量赋值
strcpy(pInfo.name, "zhangsan");
pInfo.age = 20;
printf("pInfo.index=%d\n",pInfo.index);
printf("pInfo.name=%s\n",pInfo.name);
printf("pInfo.age=%d\n",pInfo.age);
}
java的写法
public static void main(String[] args) {
StructDemo structDemo = new StructDemo();
structDemo.setIndex(0);
structDemo.setName("zhangsan");
structDemo.setAge(20);
System.out.println("index="+String.valueOf(structDemo.index));
System.out.println("name="+structDemo.name);
System.out.println("age="+String.valueOf(structDemo.age));
}
public static class StructDemo {
private int index;
private String name;
private int age;
public void setIndex(int index) {
this.index = index;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
go的写法
//定义结构体
type PersonInfo struct {
index int
name string
age int
}
func main() {
pInfo := PersonInfo{0, "zhangsan", 20} //声明并初始化结构体
pInfo.index = 1 //为结构体重新赋值
fmt.Println("index=", pInfo.index)
fmt.Println("name=", pInfo.name)
fmt.Println("age=", pInfo.age)
}
python的写法
# 使用类来实现结构体
class PersonInfo:
def __init__(self, index, name, age):
self.Index = index
self.Name = name
self.Age = age
if __name__ == "__main__":
pinfo = PersonInfo(0, "zhangsan", 20) # 声明并初始化结构体
print("index="+str(pinfo.Index))
print("name="+str(pinfo.Name))
print("age="+str(pinfo.Age))
总结对比:
1. c、c++、go中内置类型有结构体,java和python需要依靠类来间接实现结构体