小编psa*_*paz的帖子

从golang包导出接口而不是结构

下面您可以找到三种不同的方法来调用客户结构的方法Name().结果完全相同,但三个包中的每一个都导出不同的东西:

package main

import (
    "customer1"
    "customer2"
    "customer3"
    "fmt"
    "reflect"
)

func main() {

    c1 := customer1.NewCustomer("John")
    fmt.Println(c1.Name())

    c2 := customer2.NewCustomer("John")
    fmt.Println(c2.Name())

    c3 := customer3.NewCustomer("John")
    fmt.Println(c3.Name())
}
Run Code Online (Sandbox Code Playgroud)

产量

John
John
John
Run Code Online (Sandbox Code Playgroud)

customer1.go(导出Customer struct和Name()方法)

package customer1

type Customer struct {
    name string
}

func NewCustomer(name string) * Customer{
    return &Customer{name: name}
}

func (c *Customer) Name() string {
    return c.name
}
Run Code Online (Sandbox Code Playgroud)

customer2.go(不导出客户结构.仅导出Name()方法)

package customer2

type customer struct {
    name string
}

func NewCustomer(name string) *customer {
    return &customer{name: name}
}

func …
Run Code Online (Sandbox Code Playgroud)

go

6
推荐指数
1
解决办法
1291
查看次数

标签 统计

go ×1