Home  >  Article  >  Backend Development  >  Change interface value by reference

Change interface value by reference

王林
王林forward
2024-02-13 23:10:09844browse

Change interface value by reference

php editor Baicao is here to introduce a method to change the interface value through reference. In programming, sometimes we need to change the parameters of a function or method, but we do not want to directly return a new value, but want to modify the original value through a reference. In this case, we can use reference parameters. By referencing parameters, we can modify the value of the passed variable directly inside the function without returning a new value. This approach improves performance and makes the code more concise and readable. In the next article, we will explain in detail how to use reference parameters to change interface values.

Question content

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

Playground

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

Playground

Solution

Use the pointer of the roundtripper interface as the changetransport function parameter to change the value of the pointer:

// -------- 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

The above is the detailed content of Change interface value by reference. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete