代码之家  ›  专栏  ›  技术社区  ›  Arun

戈兰的吸气剂[关闭]

go
  •  -2
  • Arun  · 技术社区  · 6 年前

    我有一个名为 ProtectedCustomType 我不希望其中的变量 set get 直接由呼叫者,而是希望 Getter / Setter 方法。

    下面是我的 受保护的自定义类型

    package custom
    import "fmt"
    
    type ProtectedCustomType struct {
        name string
        age string
        phoneNumber int
    }
    
    
    
    func (pct *ProtectedCustomType) SetAge (age string)   {
        pct.age=age
        fmt.Println(pct.age)
    } 
    
    func (pct *ProtectedCustomType) GetAge ()  string  {
        return pct.age
    } 
    

    这是我的主要功能

    package main
    
    import (
        "fmt"
        "./custom"
    )
    
    var print =fmt.Println
    func structCheck2() {
        pct := custom.ProtectedCustomType{}
        pct.SetAge("23")
        age:=pct.GetAge
        print (age)
    }
    
    func main() {
        structCheck2()
    }
    

    我想把它印出来 23 ,但它正在打印为 0x48b950

    1 回复  |  直到 6 年前
        1
  •  3
  •   Adrian    6 年前

    这个(你的代码)需要 pct 实例的 GetAge 方法并将其存储在变量中:

    age:=pct.GetAge
    

    这叫 盖奇 方法并将其返回值存储在变量中:

    age:=pct.GetAge()
    

    考虑采用 Tour of Go 和阅读 Go Specification 了解go语法。

    推荐文章