@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Go: 型変換した値を変数に入れずにアドレスを得ることはできない

&string(byteArray) のように直接ポインタを得ることはできない。変数に代入してから & 演算子を使う必要がある。

package main

import "fmt"

func myLen(s *string) int {
    return len(*s)
}

func main() {
    b := []byte(`hello`)

    //NG: cannot take the address of string(b)
    //n := myLen(&string(b))

    //OK
    tmp := string(b); n := myLen(&tmp)

    fmt.Println(n)
}

https://play.golang.org/p/d3cDdKmTu-l

参考

The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

検索用キーワード

型キャスト, type casting, type conversions