admin管理员组文章数量:1293371
I'm new to Go and I'm a bit confused about the different ways to declare container variables. Specifically, I want to declare a list, and I found three different approaches:
var l1 list.List
l2 := list.New()
l3 := new(list.List)
Here's a simple example demonstrating these declarations:
package main
import (
"container/list"
"fmt"
"reflect"
)
func main() {
var l1 list.List // direct declaration
l2 := list.New() // using .New()
l3 := new(list.List) // using new()
fmt.Println(reflect.TypeOf(l1)) // list.List
fmt.Println(reflect.TypeOf(l2)) // *list.List
fmt.Println(reflect.TypeOf(l3)) // *list.List
}
I noticed that the latter two declarations (l2
and l3
) result in variables of type *list.List
, while the first one (l1
) is of type list.List.
I noticed a related question that discusses the difference between v := &Vector{} and v := new(Vector). While that question is helpful, it doesn't address the specific case of declaring the difference between direct declaration and .New() (var l1 list.List
l2 := list.New()
) and the rest method.
Could someone explain:
The differences between these three approaches in the context?
When should I use each one, and what are the implications of using one over the other?
本文标签:
版权声明:本文标题:arrays - What's the difference between .New(), directcall and new() of declaring a list? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741575469a2386255.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论