通过引用改变接口值

问题描述 投票:0回答:1
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
{}

游乐场

我也试过这个基于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

游乐场

go interface
1个回答
0
投票

使用

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
{}

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.