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
1条答案
按热度按时间xzabzqsa1#
使用
RoundTripper
接口的指针作为changeTransport
函数参数来更改指针的值:PLAYGROUND