英文:
Change interface value by reference
问题
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
英文:
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)
}
Output:
transport is nil
<nil>
Expected:
transport is nil
{}
I also tried this based on 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")
}
}
}
Output:
transport is nil
2009/11/10 23:00:00 Uff
答案1
得分: 1
使用RoundTripper
接口的指针作为changeTransport
函数的参数来改变指针的值:
// -------- 我的代码。可以改变 ------------
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
{}
英文:
Use pointer of the RoundTripper
interface as the changeTransport
function argument to change pointer's value:
// -------- 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
{}
<kbd>PLAYGROUND</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论