Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@c-yan

長さ 0 のスライスとしての nil (Go)

More than 1 year has passed since last update.

長さ 0 のスライスとしての nil (Go)

長さ 0 のスライスはmake([]T, 0)でも作れますが、基本的にはnilを使えば良いようです.

確認コード

package main

import (
    "fmt"
)

func testNil(p []byte) {
    fmt.Printf("p: %v\n", p)
    fmt.Printf("len(p): %d\n", len(p))
    fmt.Printf("cap(p): %d\n", cap(p))
    for i := range p {
        fmt.Printf("NG: %d\n", i)
    }
    fmt.Printf("p[:]: %v\n", p[:])
    fmt.Printf("append(p, 0): %v\n", append(p, 0))
}

func main() {
    testNil(nil)
}

確認結果

p: []
len(p): 0
cap(p): 0
p[:]: []
append(p, 0): [0]

追記

2019/11/13 現在最新の Go 1.13.4 で動作が変わっていないことを確認

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
c-yan

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?