在Go语言中,扩展了Map类型的类型仍然是按引用传递的吗?

huangapple go评论80阅读模式
英文:

Is a type that extends a Map still passed by reference in Go?

问题

如果在Go语言中有一个类型扩展了Map,那么这个新类型在作为函数参数时,仍然是"按引用传递"(或者说作为指针值传递)吗?还是在使用时会被复制?

示例:

type myMapType map[string][]int

func doSomething(m myMapType) myMapType{

// 做一些操作
return m
}

我想避免不必要的数据复制。所以对于上面的示例,我是否需要使用指针?

提前感谢!

英文:

If you have a type in Go, that extends a Map, is this new type still "passed by reference" (or respectively passed as a pointer value)? Or is it copied when used as a function parameter?

Example:

type myMapType map[string][]int

func doSomething(m myMapType) myMapType{

// do something
return m
}

I want to prevent unnecessary copying of data. So do I need a pointer for the above example, or not?

Thanks in advance!

答案1

得分: 0

当你声明一个类型为myMapType的变量时,其行为与map[string][]int相同。

这意味着每个myMapType的实例都可以视为map[string][]int的实例,唯一的区别在于它们的类型在某些情况下不被认为是“相同的”(如赋值、类型切换、类型断言等)。

换句话说,myMapTypemap[string][]int等价的,但不是相同的

英文:

When you declare

type myMapType map[string][]int

You now have a type called myMapType, whose behaviour is the same as map[string][]int.

It's the same as if every instance of myMapType was an instance of map[string][]int, with the only difference being that their types are not considered "the same" in cases where that matters (assignment, type switch, type assertion, etc.).

In other words, myMapType and map[string][]int are equi-valent but not identic-al.

huangapple
  • 本文由 发表于 2022年8月12日 05:57:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/73327280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定