【问题标题】:error when building , getting : "suspect or "构建时出错,得到:“怀疑或”
【发布时间】:2021-11-14 00:34:47
【问题描述】:

我在使用 go 时遇到了构建问题。我想知道这是编译器的错误还是代码的问题。

// removed the error handling for sake of clarity 

file, _ := c.FormFile("file")
openedFile, _ := file.Open()
buffer := make([]byte, 512)
n, _ := openedFile.Read(buffer)

contentType := http.DetectContentType(buffer[:n])

// doesn't work

if contentType != "image/jpeg"  || contentType != "image/png" {
  return 
}

// works 

if contentType != "image/jpeg" {
    return
}
else if contentType != "image/png" {
    return
}

错误suspect or: contentType != "image/jpeg" || contentType != "image/png"

fyi " c.FormFile("file") " 是形式 Gin gonic。但这并不重要。

【问题讨论】:

  • 除非是嫌疑人或:您的 if 语句将始终为真,因为 contentType 不能同时等于 image/jpegimage/png
  • 使用 Joe Average 类型代码检测到实际编译器错误的机会为零。
  • 当谷歌搜索时只有 2 个帖子出现,这两个问题都是引用来自编译器的错误或
  • 请注意,if ... { ... return } else 始终是多余的。删除else

标签: go debugging


【解决方案1】:

您看到的是编译器警告,但应用会运行。

你的条件永远是true:

contentType != "image/jpeg"  || contentType != "image/png" 

您将 string 变量与 2 个不同的 string 值(使用不相等)进行比较,因此其中一个肯定是 true,而 true || false 始终是 true

您很可能需要逻辑 AND:我假设您想测试内容类型是否既不是 JPEG 也不是 PNG:

if contentType != "image/jpeg" && contentType != "image/png" {
    return 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2018-10-18
    • 2018-10-04
    • 2017-10-01
    • 2016-09-06
    相关资源
    最近更新 更多