几种编程语言里的结构体

几种编程语言里的结构体,第1张

文章目录
  • 写在前面
  • 内容
    • 结构体/类
      • Java
      • Dart
      • Rust
      • Go
    • 给结构体/类添加成员方法
      • Java
      • Dart
      • Rust
      • Go
    • 继承
      • Java
      • Dart
      • Rust
      • Go
  • 参考

写在前面

前段时间了解了一些 Rust 的东西,看到它给结构体(也就是 Java 或一些语言里所说的类)添加方法的时候,跟 Java 或者 Dart 里的不太一样。最近在看 Go,发现它也是如此。这一篇主要是对几种语言里结构体的一些东西进行简单的比较。

内容 结构体/类 Java
class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Dart
class Person {
  late String name;
  late int age;

  Person(this.name, this.age);
}
Rust
struct Person {
    name: String,
    age: i16,
}
Go

Go 里的结构体需要 typestruct两个关键字

type Person struct {
	name string
	age  int
}
给结构体/类添加成员方法 Java
public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        
    }
}
Dart
class Person {
  late String name;
  late int age;

  Person(this.name, this.age);

  void sayHello() {}
}
Rust

Rust 里结构体的成员方法是在外面声明,通过 impl关键字加类名表示。成员方法里还需要 &self参数来表示是属于该类实例化后里的方法。

struct Person {
    name: String,
    age: i16,
}

impl Person {
    fn say_hello(&self) {}
}
Go

Go 和 Rust 有些相似,只是 Go 只需要声明方法,并在 func后带上类名,即可表示是类里的一个方法。

type Person struct {
	name string
	age  int
}

func (Person) sayHello() {

}
继承 Java
public class Student extends Person{
    public Student(String name, int age) {
        super(name, age);
    }
}
Dart
class Student extends Person {
  Student(String name, int age) : super(name, age);
}

Go 和 Rust 的所谓的面向对象不像 Java 和 Dart,所以它们在实现我们所说的“继承”上,会有些不一样。

Rust
struct Student {
    person: Person,
}
Go

Is Go an object-oriented language?
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).
Also, the lack of a type hierarchy makes “objects” in Go feel much more lightweight than in languages such as C++ or Java.

type Student struct {
	Person
}
参考

Is Go an object-oriented language?

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1323438.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存