英文:
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
的实例,唯一的区别在于它们的类型在某些情况下不被认为是“相同的”(如赋值、类型切换、类型断言等)。
换句话说,myMapType
和map[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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论