go언어를 사용하면서 주의 할 부분
By SeukWon Kang
1. struct embedding 한 경우 embeded struct에 exported filed 가 없으면 embeding한 struct를 gob encode를 할수 없다. ( type xxx has no exported fields 에러가남 ) 간단한 해결책은 dummy exported field를 추가 하는 것이다. ( 좀 보기 싫긴 하지만 )
- type AAA BBB 형태로 정의한 경우 AAA 형 변수와 BBB 형 변수는 대입조차 안되지만 ( 에러가 남 ) 함수 인자로는 사용할수 있다. 즉 AAA를 받는 함수에 BBB 형 변수를 인자로 사용 할수 있다. ( 물리적 형태가 같은 경우에 한해서 )
추가 수정합니다. 기본 타입인 경우는 에러가 나고 복합 타입인 경우는 에러가 나지 않습니다. 작업할때는 복합 타입이어서 착각한것 같습니다.
아래의 변경된 코드를 확인 하시면 됩니다.
package main
type INT int
func fn1( a int ) {
_ = a
}
func inttest() {
var aa INT = 3
// fn1(aa) // error
_ = aa
}
type Ivt2d [2]int
func fn2( a [2]int ) {
_ = a
}
func int2dtest() {
var aa Ivt2d = Ivt2d{4,6}
fn2( aa ) // not error
}
func main() {
}
- encoding/json 패키지를 사용해서 unit8(==byte) array 나 slice를 encode 하는 경우 이 결과를 decode하면 에러가 난다. ;;; []byte 는 base64 encode 되기 때문인데 이렇게 만든 이유는 아마도 효율 문제일것같다. ( 안그러면 json이 많이 길어진다.)
이를 해결하려면 custom marshaler를 만들거나 ( json이 길어짐 ) custom unmarshaler 를 만들면 된다.
type FloorTile uint8
type FloorTileRow []FloorTile
func (ftr *FloorTileRow) UnmarshalJSON(b []byte) error {
// log.Info("%v", string(b))
data := make([]byte, len(b))
n, err := base64.StdEncoding.Decode(data, b[1:len(b)-1])
if err != nil {
return err
}
// log.Info("floor tile row len %v", n)
*ftr = make([]FloorTile, n)
for i := 0; i < n; i++ {
(*ftr)[i] = FloorTile(data[i])
}
return nil
}
guguelike의 field 구조체의 일부인데 바이너리 데이터([]byte)로 구성되어 있는 이것을 클라이언트로 전송하려고 하다 알게 된 사실이다. 물론 라이브러리 문서(http://golang.org/pkg/encoding/json/)에 적혀 있기는 하다 딱 한줄만 ;; 이렇게.. Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string