时间:2021-06-13 08:47:08 | 栏目:Golang | 点击:次
struct和C语言的很相似,模拟出class的功能,但是不完全的!没有构造函数等!
struct的申明
import "fmt"
type Person struct {
Age int
Name string
}
func main() {
//初始化两种
a := Person{}
a.Age = 2
a.Name = "widuu"
fmt.Println(a)
b := Person{
Age: 24,
Name: "widuu",
}
fmt.Println(b)
}
import "fmt"
type Person struct {
Age int
Name string
}
func main() {
b := &Person{
Age: 24,
Name: "widuu",
}
fmt.Println(b)
G(b)
fmt.Println(b)
}
func G(per *Person) {
per.Age = 15
fmt.Println(per)
}
import "fmt"
type Person struct {
Age int
Name string
Member struct {
phone, City string
}
}
func main() {
a := Person{Age: 16, Name: "widuu"}
a.Member.phone = "13800000"
a.Member.City = "widuuweb"
fmt.Println(a)
}
import "fmt"
type Person struct {
string
int
}
func main() {
a := Person{"joe", 19}
var b Person
b = a
fmt.Println(b)
}
import "fmt"
type Person struct {
Name string
Age int
}
type student struct {
Person
work string
}
func main() {
//实例化时 如果嵌入式的结构没有数据结构的名字 就默认是类型名字Person:Person
a := student{Person: Person{Name: "widuu", Age: 19}, work: "IT"}
fmt.Println(a)
}
import "fmt"
type A struct {
Name string //这个是共有的大写 如果是小写的name就包内可以用私有的
}
type B struct {
Name string
}
func main() {
a := A{}
b := B{}
a.print()
b.print()
}
//通过type不同,来取相同的方法的名称
func (a *A) print() {
fmt.Println("A")
}
func (b *B) print() {
fmt.Println("B")
}