如何将uint64转换为uint?

huangapple go评论83阅读模式
英文:

How to convert a uint64 into uint?

问题

我有以下函数:

func (rc ResizeController) Resize(c *gin.Context) {

    height := c.Query("height")
    width := c.Query("width")
    filepath := c.Query("file")

    h, err := strconv.ParseUint(height, 10, 32)
    w, err := strconv.ParseUint(width, 10, 32)

    file, err := os.Open("./test_images/" + filepath)

    if err != nil {
        log.Fatal(err)
    }

    image, err := jpeg.Decode(file)

    if err != nil {
        log.Fatal(err)
    }

    m := resize.Resize(1000, 100, image, resize.Lanczos3)

    buf := new(bytes.Buffer)
    jpeg.Encode(buf, m, nil)
    response := buf.Bytes()

    c.Data(200, "image/jpeg", response)
}

但是我得到以下错误:

controllers/resize_controller.go:41: cannot use h (type uint64) as type uint in argument to resize.Resize
controllers/resize_controller.go:41: cannot use w (type uint64) as type uint in argument to resize.Resize

我尝试了一些不同的strconv库函数,但没有成功!

英文:

I have the following function:

func (rc ResizeController) Resize(c *gin.Context) {

	height := c.Query("height")
	width := c.Query("width")
	filepath := c.Query("file")

	h, err := strconv.ParseUint(height, 10, 32)
	w, err := strconv.ParseUint(width, 10, 32)

	file, err := os.Open("./test_images/" + filepath)

	if err != nil {
		log.Fatal(err)
	}

	image, err := jpeg.Decode(file)

	if err != nil {
		log.Fatal(err)
	}

	m := resize.Resize(1000, 100, image, resize.Lanczos3)

	buf := new(bytes.Buffer)
	jpeg.Encode(buf, m, nil)
	response := buf.Bytes()

	c.Data(200, "image/jpeg", response)
}

But I get the following error:

controllers/resize_controller.go:41: cannot use h (type uint64) as type uint in argument to resize.Resize
controllers/resize_controller.go:41: cannot use w (type uint64) as type uint in argument to resize.Resize

I've tried a few different functions from the strconv lib with no luck!

答案1

得分: 37

不需要使用任何strconv函数;只需进行类型转换uint

h64, err := strconv.ParseUint(height, 10, 32)
if err != nil {
    // TODO: 处理错误
}
w64, err := strconv.ParseUint(width, 10, 32)
if err != nil {
    // TODO: 处理错误
}
h := uint(h64)
w := uint(w64)
英文:

No need to use any of the strconv functions; just do a type conversion to uint:

h64, err := strconv.ParseUint(height, 10, 32)
if err != nil {
    // TODO: handle error
}
w64, err := strconv.ParseUint(width, 10, 32)
if err != nil {
    // TODO: handle error
}
h := uint(h64)
w := uint(w64)

huangapple
  • 本文由 发表于 2015年9月3日 04:35:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/32362612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定