2017-02-25 50 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