英文:
How to send a slice to a function in Go?
问题
我正在将一些C代码改写成Go代码。在我的C代码中,有这样的内容:
static void sharedb(unsigned char *sharedkey, unsigned char *send,
const unsigned char *received) {
unsigned char krq[96];
unsigned char buf[64];
// 其余部分省略
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代码中,我使用了byte
数组来代替char
数组。我有类似这样的代码:
func SharedB(sharedKey, send, received []byte) {
var krq [96]byte
var buf [64]byte
// 其余部分省略
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代码?此外,我在Go函数参数中是否应该使用指针符号*
,就像在C中一样?
英文:
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?
答案1
得分: 7
指定长度的参数(例如[SharedKeyBytes]byte
)是数组,而不是切片;因此,您不能传递切片,这就是类型不匹配的错误。您可以选择:
- 将参数类型更改为切片(
[]byte
) - 在调用函数之前将切片复制到适当大小的数组中,然后将数组传递给函数而不是切片(playground示例)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论