0
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 1 year has passed since last update.

Go言語でstring型の値を保持した配列をstrings.Joinしようとしたらエラーが発生

Posted at

発生したエラー

Go言語でstring型の値を保持した配列をカンマ区切りで結合したい時に、以下のエラーが発生

package main
import "fmt"
import "strings"
import "strconv"

func main(){
    var numbers[1000]string
    for i := 0; i < 1000; i++ {
        numbers[i] = strconv.Itoa(i+1)
    }
    //誤り
    fmt.Println(strings.Join(numbers, " "))
}
# command-line-arguments
./Main.go:12:29: cannot use numbers (type [1000]string) as type []string in argument to strings.Join

解決策

strings.Joinの引数はSliceであるため、Array型の変数を引数に取ることができない。
そのため、ArrayをSliceに変換してJoinして出力する。

package main
import "fmt"
import "strings"
import "strconv"

func main(){
    var numbers[1000]string
    for i := 0; i < 1000; i++ {
        numbers[i] = strconv.Itoa(i+1)
    }
    //誤り
    fmt.Println(strings.Join(numbers, " "))
    //正しい例
    fmt.Println(strings.Join(numbers[:], " "))
}
0
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
0
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?