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

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

问题描述:

I'm rewriting some C code in Go. And in my C code I have stuff like this:

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);
}

Where indcpa_enc function is defined like this:

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

So, in my Go code instead of using char arrays I used byte arrays. Where I have something like this:

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])
}

Where INDCPAEnc function is defined like this:

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

Though, this function call in Go gives me an array, regarding type mismatch. How can I convert a C code like above to a proper Go code? Also, should I use the pointer notation * for my Go function parameters as in C?

我正在用Go重写一些C代码。 在我的C代码中,我有这样的东西: p>

  static void sharedb(unsigned char * sharedkey,unsigned char * send,
 const unsigned char * received){
  unsigned char krq [96];  
 unsigned char buf [64]; 
 //为简洁起见,删除其余部分
 
 indcpa_enc(发送,buf,已接收,krq + 32); 
} 
  code>  pre> 
 \  n 

其中 indcpa_enc code>函数的定义如下: p>

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

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

  func Sh​​aredB(sharedKey,发送,接收[] byte){
 var krq [96] byte 
 var buf [64] byte  
 
 //为了简洁起见,删除其余部分
 
 INDCPAEnc(发送[:],buf [:SharedKeyBytes],接收[:],krq [32:32 + CoinBytes])
} 
  code>   pre> 
 
 

函数 INDCPAEnc code>的定义如下: p>

  func INDCPAEnc(c [] byte,m [  SharedKeyBytes] byte,pk [] byte,硬币[CoinBytes] byte)
  code>  pre> 
 
 

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

The parameters that specify a length (e.g. [SharedKeyBytes]byte) are arrays, not slices; therefor, you cannot pass a slice, hence the type mismatch error. You can either:

  • Change the parameter type to slice ([]byte)
  • Copy the slice to an appropriately-sized array prior to calling the function, then pass the array to the function instead of the slice (playground example)