1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Goのintスライスの値をスペース区切りで出力

Posted at

int型のスライスのままではstrings.Join()できない

main.go
package main
import (
    "fmt"
    "strings"
)

func main() {
    intSl := []int{1, 2, 3}
    fmt.Println(strings.Join(intSl, " "))
    // => cannot use intSl (type []int) as type []string in argument to strings.Join
    // strings.Join()の第一引数はstring型のスライスでなければいけない
}

string型のスライスを作ってからstrings.Join()する

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    intSl := []int{1, 2, 3}
    strSl := []string{}
    for _, v := range intSl {
        // intSlの値を文字列にしてstrSlに突っ込む
        strSl = append(strSl, strconv.Itoa(v))
    }
    fmt.Println(strings.Join(strSl, " "))
    // => 1 2 3
}

ついでに

Pythonならリスト内包表記で1行で書ける

python.py
nums = [1, 2, 3]
print(" ".join([str(num) for num in nums]))
# => 1 2 3
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?