繁体   English   中英

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

[英]How to send a slice to a function in 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
  • 在调用函数之前,将切片复制到适当大小的数组,然后将数组而不是切片传递给函数( 游乐场示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM