菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
3043
0

struct 结构体 -Go 学习记录

原创
05/13 14:22
阅读数 1554

实例创建及初始化

  • 基本使用

    func TestInitEmployee(t *testing.T) {
    type Employee struct {
        Id   int
        Name string
        Age  int
    }
    e  := Employee{"0", "Bob", 20}
    e1 := Employee{name: "Ali", Age: 30}
    // 注意这里返回的引用/指针, 相当于 e:= &Employee{}
    e2 := new(Employee)
    // 与其他的编程语言不同, 可以不用 -> 的方式来访问指定的属性
    e2.Id = "2"
    e2.Age = 23
    e2.Name = "Ali"
    // 访问
    t.Log(e1.Id)           // 0
    t.Logf("e is %T", e)   // e is employee_test.Employee 前面如果加上 &  那么返回的也是 指针类型
    t.Logf("e2 is %T", e2) // e2 is *employee_test.Employee 这个是指针类型
    }
  • 非指针传递会生成一个新的结构对象,其中每个成员会复制。指针传递,只是传递指针,且该指针指向原有结构。

// 这一种,定义方式在实例对应方法变调用的时候 ,实例的成员会进行值复制
    func (e Employee) String() string {
          fmt.Printf("输出自己的e的地址 %x\n", unsafe.Pointer(&e.Name)) // c00000a0e8
          return fmt.Sprintf("ID :%d-Name:%s-Age:%d", e.Id, e.Name, e.Age)
    }

// 在通常情况下避免内存拷贝我们使用 这种方式
    func (e *Employee) String() string {
        fmt.Printf("输出自己的e的地址 %x\n", unsafe.Pointer(&e.Name)) // c00000a0e8
        return fmt.Sprintf("ID :%d/Name:%s/Age:%d", e.Id, e.Name, e.Age)
    }

// 测试 String 方法
    func TestInit(t *testing.T) {
        e := Employee{1, "Bob", 20}
        // 第一种
        // t.Log(e.String())  // ID :1-Name:Bob-Age:20
        fmt.Printf("输出传进来的e的地址 %x\n", unsafe.Pointer(&e.Name)) // c00000a108

        // 第二种
        t.Log(e.String()) // ID :1/Name:Bob/Age:20
        fmt.Printf("输出传进来的e的地址 %x\n", unsafe.Pointer(&e.Name))  // c00000a0e8

    }

如想看学习记录同步的练习代码移步 GitHub

发表评论

0/200
3043 点赞
0 评论
收藏
为你推荐 换一批