dongyou6768 2018-11-21 16:53
浏览 87

声明和不使用逻辑[重复]

Take this incredibly simple example. which shows variable assignment in and out of a block.

On compilation this results in: u declared and not used

var u string
{
    u, err := url.Parse("http://bing.com/search?q=dotnet")
    if err != nil {
        log.Fatal(err)
    }
}
log.Debug(u)

This simulates a logic block during which we might assess several things and set a var to the value we like depending on logic evaluation. How is this possible?

</div>
  • 写回答

1条回答 默认 最新

  • dshkmamau65777662 2018-11-21 16:59
    关注

    Please pay attention that:

    u, err := url.Parse("http://bing.com/search?q=dotnet")
    

    in this line of code you have block scoped variable u which is differ from those one which declared in line: var u string, hence you have this error.
    Moreover here you have shadowing for variable u from outer block scope which may lead to bugs, see this:

    var u string
    u = "blank"
    {
        u, err := url.Parse("http://bing.com/search?q=dotnet")
        if err != nil {
            log.Fatal(err)
        }
        log.Printf("%#v", u)
    }
    log.Printf("%#v", u)
    

    Result will be:

    2018/11/21 19:12:33 &url.URL{Scheme:"http", Opaque:"", User:(*url.Userinfo)(nil), Host:"bing.com", Path:"/search", RawPath:"", ForceQuery:false, RawQuery:"q=dotnet", Fragment:""}
    2018/11/21 19:12:33 "blank"
    

    As you can see here you have even different data types, and variable u not changed after this block.

    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写