dpict99695329 2019-08-07 15:59 采纳率: 100%
浏览 92
已采纳

Go中[] Foo(nil)和[] Foo {}之间的区别

I'm new to Go and would like to know the difference between []Foo(nil) and []Foo{}.

(I'm using this in my tests, where I want to specify that when my function errors, it should return nil, err. The go linter complains when I use nil or []Foo{}, but works when I use []Foo(nil).)

What I've tried

I had a look at the Go docs and on SO and found Struct stuff about Foo{} but not []Foo(nil).

When I use []Foo{}, the test failure outputs:

expected: []Foo{}
actual  : []Foo(nil)

Fmt outputs for []Foo(nil) and []Foo{} are the same:

fmt.Println([]Foo(nil)) // []
fmt.Println([]Foo(){}) // []
fmt.Printf([]Foo(nil)) // []Foo
fmt.Printf([]Foo(){}) // []Foo

I noticed that if I write just Foo(nil) (without the []) then the linter complains about cannot convert nil to type Foo.

So my only guess is that []Foo(nil) invokes some type coercion. Can anyone help me out?

  • 写回答

1条回答 默认 最新

  • dsa5233 2019-08-07 16:04
    关注

    The expression []Foo(nil) is a conversion. It converts the untyped nil to a nil slice of type []Foo.

    The expression []Foo{} is a composite literal that returns a empty slice. It's empty because no elements are listed between the {}.

    This might help explain the difference:

    fmt.Println([]Foo(nil) == nil) // prints true
    fmt.Println([]Foo{} == nil)    // prints false
    

    A nil slice does not have a backing array. An empty slice has a backing array with length 0.

    What's confusing is that the fmt package can output the same data for empty slices and nil slices.

    If the distinction between a nil slice and empty slice is not important in your tests, then test with len(s) == 0. This expression evaluates to true for both nil slices and empty slices.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi