构建时出错,得到:“怀疑或”

jay*_*ayD 10 debugging go

我在使用 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
}
Run Code Online (Sandbox Code Playgroud)

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

仅供参考 " c.FormFile("file") " 是形式 Gin gonic。但这并不重要。

icz*_*cza 33

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

您的情况始终是true

contentType != "image/jpeg"  || contentType != "image/png" 
Run Code Online (Sandbox Code Playgroud)

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

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

if contentType != "image/jpeg" && contentType != "image/png" {
    return 
}
Run Code Online (Sandbox Code Playgroud)