Go语言 通过引用更改接口值

beq87vna  于 2023-05-04  发布在  Go
关注(0)|答案(1)|浏览(108)
package main

import (
    "fmt"
)

// -------- Library code. Can't change ------------
type Client struct {
    transport RoundTripper
}

type RoundTripper interface {
    Do()
}

type Transport struct{}

func (d Transport) Do() {}

var DefaultTransport RoundTripper = Transport{}

// -------- My code. Can change ------------
func changeTransport(r RoundTripper) {
    if r == nil {
        fmt.Println("transport is nil")
        r = DefaultTransport
    }
}

func main() {
    c := Client{}
    changeTransport(c.transport)
    fmt.Println(c.transport)
}

输出:

transport is nil
<nil>

预期:

transport is nil
{}

Playground
我也尝试了基于https://stackoverflow.com/a/44905592/6740589的方法:

func changeTransport(r RoundTripper) {
    if r == nil {
        fmt.Println("transport is nil")
        d, ok := DefaultTransport.(Transport)
        if !ok {
            log.Fatal("impossible")
        }

        if t, ok := r.(*Transport); ok {
            t = &d
            fmt.Println("ignoreme", t)
        } else {
            log.Fatal("Uff")
        }

    }
}

输出:

transport is nil
2009/11/10 23:00:00 Uff

Playground

xzabzqsa

xzabzqsa1#

使用RoundTripper接口的指针作为changeTransport函数参数来更改指针的值:

// -------- My code. Can change ------------
func changeTransport(r *RoundTripper) {
    if r != nil && *r == nil {
        fmt.Println("transport is nil")
        *r = DefaultTransport
    }
}

func main() {
    c := Client{}
    changeTransport(&c.transport)
    fmt.Println(c.transport)
}
transport is nil
{}

PLAYGROUND

相关问题