如何在Go中向函数发送切片?

错别字:

我正在Go中重写一些C代码。在我的C代码中,我有类似以下内容:

static void sharedb(unsigned char *sharedkey, unsigned char *send,
                    const unsigned char *received) {
    unsigned char krq[96]; 
    unsigned char buf[64];
    // rest removed for brevity

    indcpa_enc(send, buf, received, krq + 32);
}

indcpa_enc函数的定义如下:

static void indcpa_enc(unsigned char *c,
                       const unsigned char *m,
                       const unsigned char *pk,
                       const unsigned char *coins)

因此,在我的Go代码中,我没有使用char数组,而是使用了byte数组。我有这样的地方:

func SharedB(sharedKey, send, received []byte) {
    var krq [96]byte
    var buf [64]byte

    // rest removed for brevity

    INDCPAEnc(send[:], buf[:SharedKeyBytes], received[:], krq[32:32+CoinBytes])
}

INDCPAEnc函数的定义如下:

func INDCPAEnc(c []byte, m [SharedKeyBytes]byte, pk []byte, coins [CoinBytes]byte) 

不过,Go中的此函数调用为我提供了一个有关类型不匹配的数组。如何将上述C代码转换为正确的Go代码?另外,是否应该*像在C中那样对Go函数参数使用指针符号

阿德里安:

指定长度的参数(例如[SharedKeyBytes]byte)是数组,而不是切片;因此,您无法传递切片,因此类型不匹配错误。您可以:

  • 将参数类型更改为slice([]byte
  • 在调用函数之前,将切片复制到适当大小的数组,然后将数组而不是切片传递给函数(游乐场示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章