Go语言学习: client + methods 类/class

常用的 client + methods
更新于: 2024-11-16 11:06:40

实现

type Client struct {
  authKey string // private authKey set in constructors
}

func NewClient() *Client { // default constructor
  return &Client{}
}

func NewClientWithAuth(key string) *Client { // 'With' Constructor
  return &Client{key}
}

func (c *Client) AuthKey() string {
   if c.authKey != "" {
      return c.authKey
   }
   return "default-auth-key"
}

使用

package main

import "fmt"

func main() {
  client := NewClient()
  fmt.Println(client.AuthKey()) // default-auth-key
}