GO 指標*&問題疑問

lik0914發表於2018-02-02
package main

import (
    "fmt"
)

func main() {
    //var t *stuffClient = NewStuffClient(Connection{})
    //fmt.Println(*t)
    x := NewStuffClient(Connection{})
    fmt.Println(x) // prints &{{} 2 3}
    x = NewStuffClient(
        Connection{},
        WithRetries(1),
    )
    fmt.Println(x) // prints &{{} 2 1}
    x = NewStuffClient(
        Connection{},
        WithRetries(1),
        WithTimeout(1),
    )
    fmt.Println(x) // prints &{{} 1 1}
}

var defaultStuffClientOptions = StuffClientOptions{
    Retries: 3,
    Timeout: 2,
}
type StuffClientOption func(*StuffClientOptions)
type StuffClientOptions struct {
    Retries int //number of times to retry the request before giving up
    Timeout int //connection timeout in seconds
}
func WithRetries(r int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Retries = r
    }
}
func WithTimeout(t int) StuffClientOption {
    return func(o *StuffClientOptions) {
        o.Timeout = t
    }
}
type StuffClient interface {
    DoStuff() error
}
type stuffClient struct {
    conn    Connection
    timeout int
    retries int
}

type Connection struct {}

func NewStuffClient(conn Connection, opts ...StuffClientOption) StuffClient {
    options := defaultStuffClientOptions
    for _, o := range opts {
        o(&options)
    }
    return &stuffClient{
        conn:    conn,
        retries: options.Retries,
        timeout: options.Timeout,
    }
}
func (c stuffClient) DoStuff() error {
    return nil
}

列印的結果

//&{{} 2 3}
//&{{} 2 1}
//&{{} 1 1}

嘗試*取值操作列印結果報錯

fmt.Println(*x)
//prog.go:11:17: invalid indirect of x (type StuffClient)
//Program exited.

如果介面不能進去*取值操作,那 func return 為啥返回&呢?

更多原創文章乾貨分享,請關注公眾號
  • GO 指標*&問題疑問
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章