2017-02-25 51 views
-1

我想用golang閱讀二進制文件,但有一個問題。去 - 閱讀與結構的二進制文件

如果我讀它這樣,一切都將被罰款

package main 

import (
    "encoding/binary" 
    "fmt" 
    "os" 
) 

type Header struct { 
    str1 int32 
    str2 [255]byte 
    str3 float64 
} 

func main() { 

    path := "test.BIN" 

    file, _ := os.Open(path) 

    defer file.Close() 

    thing := Header{} 
    binary.Read(file, binary.LittleEndian, &thing.str1) 
    binary.Read(file, binary.LittleEndian, &thing.str2) 
    binary.Read(file, binary.LittleEndian, &thing.str3) 

    fmt.Println(thing) 
} 

但如果我優化.Read-科

binary.Read(file, binary.LittleEndian, &thing) 
//binary.Read(file, binary.LittleEndian, &thing.str1) 
//binary.Read(file, binary.LittleEndian, &thing.str2) 
//binary.Read(file, binary.LittleEndian, &thing.str3) 

我得到以下錯誤:

panic: reflect: reflect.Value.SetInt using value obtained using unexported field 

有人可以說我爲什麼嗎?

所有例子期運用了 「優化路」

謝謝:)

回答

1

str1str2str3是不導出。這意味着其他軟件包無法看到它們。要導出它們,請將第一個字母大寫。

type Header struct { 
    Str1 int32 
    Str2 [255]byte 
    Str3 float64 
} 
+0

謝謝:)現在我知道(聯合國)導出的消息:)) – overboarded