gpt4 book ai didi

转到不匹配的类型 uint64 和 int32

转载 作者:IT王子 更新时间:2023-10-29 01:45:24 25 4
gpt4 key购买 nike

对于这个错误,我看不出我在做什么错,两者都是 syscall.Timeval Usec 类型

谢谢

package common

import (
"syscall"
)

func getUsecSince(oldTime syscall.Timeval) (result uint64) {
now := syscall.Timeval{}
syscall.Gettimeofday(&now)

for now.Sec > oldTime.Sec {
result += 1000000
now.Sec--
}
return result + (now.Usec - oldTime.Usec)
}

./common.go:15: invalid operation: result + (now.Usec - oldTime.Usec) (mismatched types uint64 and int32)

最佳答案

使用带符号的返回值 (int64),例如 Timeval.SecTimeval.Usec。使用 TimevalToNsec 实现跨操作系统的可移植性。例如,Timeval 字段可以是 int32int64。为了获得正确的结果,请使用,

package main

import (
"fmt"
"syscall"
"time"
)

func getUsecSince(old syscall.Timeval) int64 {
var now syscall.Timeval
syscall.Gettimeofday(&now)
nsecs := syscall.TimevalToNsec(now) - syscall.TimevalToNsec(old)
return nsecs / int64(time.Microsecond)
}

func main() {
old := syscall.Timeval{}
syscall.Gettimeofday(&old)
time.Sleep(2*time.Second + 42*time.Microsecond)
fmt.Println(getUsecSince(old))
}

输出:

2000377

关于转到不匹配的类型 uint64 和 int32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com