-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstruct.go
More file actions
50 lines (40 loc) · 1.23 KB
/
struct.go
File metadata and controls
50 lines (40 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import "fmt"
// 基本结构体
type Person struct {
Name string
Age int
Address string
}
// 构造函数(Go 没有正式的构造函数,但可以使用工厂函数)
func NewPerson(name string, age int, address string) *Person {
return &Person{name, age, address}
}
// 方法
func (p *Person) Introduce() {
fmt.Printf("Hi, I am %s, %d years old, from %s.\n", p.Name, p.Age, p.Address)
}
// 继承示例(通过嵌套结构体)
type Employee struct {
Person // 嵌入Person结构体,模拟继承
Position string
}
// 构造函数
func NewEmployee(name string, age int, address string, position string) *Employee {
return &Employee{Person: Person{name, age, address}, Position: position}
}
// 方法覆盖
func (e *Employee) Introduce() {
fmt.Printf("I am %s, a %s at the company, living in %s.\n", e.Name, e.Position, e.Address)
}
func main() {
p1 := NewPerson("Alice", 30, "123 Main St")
p1.Introduce()
e1 := NewEmployee("Bob", 28, "456 Elm St", "Software Developer")
e1.Introduce() // 覆盖了Person的Introduce方法
}
/*
jarry@MacBook-Pro struct % go run struct.go
Hi, I am Alice, 30 years old, from 123 Main St.
I am Bob, a Software Developer at the company, living in 456 Elm St.
*/