doujing8435 2013-04-02 20:42
浏览 37
已采纳

为什么在if语句中创建结构在Go中是非法的?

Go complains about instantiating a struct in an if-statement. Why? Is there correct syntax for this that doesn't involve temporary variables or new functions?

type Auth struct {
    Username    string
    Password    string
}

func main() {
    auth := Auth { Username : "abc", Password : "123" }

    if auth == Auth {Username: "abc", Password: "123"} {
        fmt.Println(auth)
    }
}

Error (on the if-statement line): syntax error: unexpected :, expecting := or = or comma

This yields the same error:

if auth2 := Auth {Username: "abc", Password: "123"}; auth == auth2 {
            fmt.Println(auth)
}

This works as expected:

auth2 := Auth {Username: "abc", Password: "123"};
if  auth == auth2 {
        fmt.Println(auth)
}
  • 写回答

1条回答 默认 最新

  • dqrmkdu25623 2013-04-02 20:49
    关注

    You have to surround the right side of the == with parenthesis. Otherwise go will think that the '{' is the beginning of the 'if' block. The following code works fine:

    package main
    
    import "fmt"
    
    type Auth struct {
        Username    string
        Password    string
    }
    
    func main() {
        auth := Auth { Username : "abc", Password : "123" }
        if auth == (Auth {Username: "abc", Password: "123"}) {
            fmt.Println(auth)
        }
    }
    
    // Output: {abc 123}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式