Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不改变golang中原始值的情况下修改对象值的副本?_Go_Types_Interface - Fatal编程技术网

如何在不改变golang中原始值的情况下修改对象值的副本?

如何在不改变golang中原始值的情况下修改对象值的副本?,go,types,interface,Go,Types,Interface,在改变物品的价值方面遇到了一些问题。我对Goaling也是新手。请考虑下面的例子。 //interface type A interface{ GetVal() interface{} } //type which implements interface A type B struct{ Val interface{} } func (j *B)GetVal() interface{}{ return j.Val } //function where object of B is get

在改变物品的价值方面遇到了一些问题。我对Goaling也是新手。请考虑下面的例子。

//interface
type A interface{
GetVal() interface{}
}

//type which implements interface A
type B struct{
Val interface{}
}

func (j *B)GetVal() interface{}{
return j.Val
}

//function where object of B is getting created
func exmaple1(){
obj := &B{Val:"25"}
Example2(obj)
}


func Example2(handler A){
val := handler.GetVal()
example3(val1)
}

func example3(val1 interface{}){
// do some modifiaction on val1
}
我这里的问题是,如果我只想将val1(在示例3中)修改为不同的值,比如10,它不应该改变原始值处理程序.GetVal(),示例25。我该怎么做??。如何创建handler.GetVal()的副本并传递给函数example3,以便只更改其副本而不是原始副本

还有一个问题与上述问题有关 我不是将对象值作为字符串传递,而是将值作为map[sting]接口{}传递,如下例所示,并在exmaple3中修改它以添加新键

包干管

import (
    "fmt"
)

type A interface{
GetVal() interface{}
}

//type which implements interface A
type B struct{
Val interface{}
}

func (j *B)GetVal() interface{}{
return j.Val
}



func Example2(handler A){
val := handler.GetVal()
example3(val)
}

func example3(val1 interface{}){
// do some modifiaction on val1
val1.(map[string]interface{})["password"] = "heloo"

}
func main(){

obj := &B{Val:map[string]interface{}{"userName": "noob"}}
Example2(obj)

fmt.Println(obj)
}
在这里,如果我修改示例3中的val1(例如:添加一个新密钥),obj也会通过添加新密钥而改变。如何避免这种情况?原因是什么。?我不想改变原来的obj。只有它的副本应该被改变。如何创建obj的副本并将其传递给示例3,以便只修改其副本而不修改原始obj。如何实现


正如@Muffin指出的,
example3
不会修改
val1
。如果确实要修改值,则需要使用
指针接收器

package main

import (
    "fmt"
)

//interface
type A interface {
    GetVal() interface{}
    SetVal(val interface{})
}

//type which implements interface A
type B struct {
    Val interface{}
}

func (j *B) GetVal() interface{} {
    return j.Val
}

func (j *B) SetVal(v interface{}) {
    j.Val = v
}

func Example(handler A) {
    val := handler.GetVal()
    inner(val)
}
func inner(val1 interface{}) {
    // do some modifiaction on val1
    val1 = 100
}

func SetExample(handler A, v interface{}) {
    handler.SetVal(v)
}

func main() {
    obj := &B{Val: "25"}
    Example(obj)
    fmt.Println(obj)

    SetExample(obj, 100)
    fmt.Println(obj)

}


示例3
中显示修改
val1
的代码。thanks@tomkaith13@松饼。添加了与此问题相关的最后一个示例。