GoLang == true评估但未使用

问题描述 投票:1回答:4

在代码中,我尝试做一些操作

is_html := false;

// Check, if HTMl is exist 
for i := 0; i < len(modules_arr); i++ { 
    if modules_arr[i] == "html" { is_html := true }

}

if is_html ==true
{
    fmt.Printf("%v", "asdasd")
}

但是我收到一个错误:

./api.go:26: missing condition in if statement
./api.go:26: is_html == true evaluated but not used
Error: process exited with code 2.
go syntax
4个回答
9
投票

if语句需要{在同一行

这意味着你做不到

if is_html ==true
{
    fmt.Printf("%v", "asdasd")
}

正确的代码是

if is_html ==true {
    fmt.Printf("%v", "asdasd")
}

阅读http://golang.org/doc/effective_go.html#semicolons以获得更好的理解


1
投票

例如,

package main

import "fmt"

func main() {
    modules_arr := []string{"net", "html"}
    is_html := false
    // Check, if HTMl is exist
    for i := 0; i < len(modules_arr); i++ {
        if modules_arr[i] == "html" {
            is_html = true
        }
    }
    if is_html == true {
        fmt.Printf("%v", "asdasd")
    }
}

输出:

asdasd

声明is_html := true声明了一个新变量,隐藏了声明is_html := false中声明的变量。写is_html = true以使用先前声明的变量。


1
投票

例如,

package main

func main() {
    modules_arr := []string{"asd", "html"}
    is_html := false

    for i := 0; i < len(modules_arr); i++ {
        if modules_arr[i] == "html" {
            is_html = true
        }

    }
    //or
    for _, value := range modules_arr {
        if value == "html" {
            is_html = true
        }
    }

    if is_html {//<- the problem is here! We Can't move this bracket to the next line without errors, but we can leave the expression's second part
        print("its ok.")
    }
}

0
投票

正如@Dustin已经指出的那样,它应该是isHtml

https://play.golang.org/p/Whr4jJs_ZQG

package main

import (
    "fmt"
)

func main() {
    isHtml := false

    if isHtml {
        fmt.Println("isHtml is true")
    }

    if !isHtml {
        fmt.Println("isHtml is false")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.