2013-05-02 62 views

回答

14

我假設你想要的東西就像C處理這件事一樣。沒有建立的方式來做到這一點。你必須爲你的結構定義自己的序列化和反序列化。二進制包將幫助您將結構中的字段編碼爲可添加到字節數組中的字節,但您將負責指定字節數組中的長度和偏移量,以保存結構中的字段。

您的其他選項是使用編碼包之一:http://golang.org/pkg/encoding/如gob或json。

編輯:

既然你想這個製作的哈希,你在你的評論說做easisest就是使用[]byte(fmt.Sprintf("%v", struct))像這樣:http://play.golang.org/p/yY8mSdZ_kf

+0

感謝您的快速回答。我試圖做到這一點的原因是能夠得到我的結構散列(我試圖使用SHA-256,但它可能是另一個)。你知道更簡單的方法嗎? – abw333 2013-05-02 04:56:21

+1

我編輯了答案,以顯示一個簡單的方法來做你想做的。 – 2013-05-02 05:06:00

+0

再次感謝。我試過這樣做,但我收到以下錯誤消息:「單值上下文中的多值fmt.Printf()」。你知道這是爲什麼嗎? – abw333 2013-05-02 05:18:31

7

應使用而不是字符串一個字節的緩衝區,另一個建議的方法創建可變長度的SHA1,所述SHA1標準長度必須爲20個字節(160位)

package main 

import (
    "crypto/sha1" 
    "fmt" 
    "encoding/binary" 
    "bytes" 
) 

type myStruct struct { 
    ID string 
    Data string 
} 

func main() { 
    var bin_buf bytes.Buffer 
    x := myStruct{"1", "Hello"} 
    binary.Write(&bin_buf, binary.BigEndian, x) 
    fmt.Printf("% x", sha1.Sum(bin_buf.Bytes())) 
} 

試一試: http://play.golang.org/p/8YuM6VIlLV

這是一個非常簡單的方法,它的效果很好。

+1

不支持鏈接的答案已棄用。 – 2015-01-21 17:38:38

+0

謝謝Der,我會編輯這個。是我的第一個評論。 – 2015-01-22 18:13:20

+7

看起來不像這樣,因爲'myStruct'不是固定大小。 HTTPS://play.golang。org/p/IGA_lgRVNX – 2016-09-21 21:00:08

1

一個可能的解決方案是"encoding/gob"標準包。 gob包創建了一個編碼器/解碼器,可以將任何結構編碼成一個字節數組,然後將該數組解碼回結構。有一個很棒的帖子,here

正如其他人指出的那樣,有必要使用這樣的包,因爲結構本質上具有未知大小,並且不能轉換爲字節數組。

我已經包含了一些代碼和play

package main 

import (
    "bytes" 
    "encoding/gob" 
    "fmt" 
    "log" 
) 

type P struct { 
    X, Y, Z int 
    Name string 
} 

type Q struct { 
    X, Y *int32 
    Name string 
} 

func main() { 
    // Initialize the encoder and decoder. Normally enc and dec would be 
    // bound to network connections and the encoder and decoder would 
    // run in different processes. 
    var network bytes.Buffer  // Stand-in for a network connection 
    enc := gob.NewEncoder(&network) // Will write to network. 
    dec := gob.NewDecoder(&network) // Will read from network. 
    // Encode (send) the value. 
    err := enc.Encode(P{3, 4, 5, "Pythagoras"}) 
    if err != nil { 
     log.Fatal("encode error:", err) 
    } 

    // HERE ARE YOUR BYTES!!!! 
    fmt.Println(network.Bytes()) 

    // Decode (receive) the value. 
    var q Q 
    err = dec.Decode(&q) 
    if err != nil { 
     log.Fatal("decode error:", err) 
    } 
    fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) 
} 
相關問題