您的位置 首页 golang

Golang编程中遇到的小陷阱

1.int类型和float类型不能匹配

go语言规定不允许在整数型变量和浮点型变量之间进行任何数学运算。错误例子如下:

参考:go语言中文文档:www.topgoer.com

转自:

     var n, m = 21, 2.1
    // 下面一行会报错:invalid operation: n / m (mismatched types int and float64)
    fmt.Println(n / m)   

改正结果如下:

     var n = 21 / 2.1
    fmt.Println(n)  

2.int类型和time.Duration类型不能匹配

go语言规定数值运算的操作数必须具有相同的类型,除非该操作包含类型转换或非类型化常量。错误例子如下:

     var n = 3
        // 下面一行会报错:invalid operation: timeout * time.Millisecond (mismatched types int and time.Duration)
    fmt.Println(n * time.Millisecond)  

改正结果如下:

     // 1. 使用常量
    const n = 3
    fmt.Println(n * time.Millisecond)
 
    // 2. 使用相同类型
    var n time.Duration = 10
    fmt.Println(n * time.Millisecond)  

3.结构体struct

1)声明指针结构体时,如果未初始化,则初始值为nil,因此只有初始化后,才能访问字段或为字段赋值。例子如下:

 type City struct {
    Name string
}
 
var c *City
// 错误用法, 未初始化, c为nil
c.Name = "Osaka" 
c = &City{}
// 初始化后,结构体指针指向某个结构体地址,才能访问字段,为字段赋值
c.Name = "Tokyo" 
 
// 因此,常用的做法如下
c := &City{}    
c.Name = "London"    

2)使用Go内置new()函数,可以分配内存来初始化结构休,并返回分配的内存指针,因为已经初始化了,所以可以直接访问字段。例子如下:

 var c = new(City)
c.Name = "NewYork"  

3)因为把结构体传给函数是值传递,所以在函数内修改结构体的字段并不会影响原结构体,但如果将指针结构体传给函数,则在函数中使用指针对结构体所做的修改,都会影响到指针指向的结构体。例子如下:

 func main() {
    c1 := City{}
    c2 := new(City)
    Change(c1,c2)
    fmt.Println(c1,c2)
}

func Change(c1 City,c2 *City){
     c1.Name = "Tokyo"
    c2.Name = "NewYork"
}  

4)结构体不能包含自身,比如City中的字段不能是City类型,但可以是*City,例子如下:

 type City struct {
   Name string
   Next City  // 这种形式的定义是错误的
}

type City struct {
   Name string
   Next *City // 这种形式的定义是正确的
}  

其他诸如声明一个map不能立即赋值,类型断言失败会panic,二次关闭一个channel也会panic等比较常见的就暂时不详细介绍啦

Golang编程中遇到的小陷阱

文章来源:智云一二三科技

文章标题:Golang编程中遇到的小陷阱

文章地址:https://www.zhihuclub.com/86630.shtml

关于作者: 智云科技

热门文章

评论已关闭

30条评论

  1. Apply a rich moisturizer several times a day, especially right after you bathe or wash your hands

  2. Many environmental agents are reported to cause hepatocellular carcinoma HCC c TP, TPP, TiCa, and TD

  3. Conclusion The combination of gemcitabine and tamoxifen appears to be an innovative therapeutic approach in the management of APC with interesting clinical activity and a good profile of toxicity J Natl Cancer Inst Monogr 30 56 61

  4. He showed that the concentration of an agent reaches an equilibrium value at the receptor after an exposure of infinite duration because elimination counterbalances the uptake of the agent

  5. Please provide any additional studies or scientific information that support or validate evidence based strategies or approaches for controlling exposures to hazardous drugs that are different from those that NIOSH has proposed J Environ Public Health

  6. The relevance of a Gly 6 Leu 7 ОІ turn conformation for the biological activity of GnRH is supported by the increased potency of GnRH analogs in which d residues have been incorporated into the 6 position Monahan et al The predominant histological types were simple tubulopapillary n 176; 50

  7. 197 Level of evidence 3iiA The tumors were located in various sites including the extremities, abdomen, and orbit

  8. Diagnosing cancer in pregnancy can pose a significant challenge for patients and providers Epub 2017 Sep 25

  9. 34 grade 1 3 AEs related to thalidomide were reported with an average incidence rate of 45 00378 6679 Sunitinib Malate Mylan Pharmaceuticals Inc

  10. Azithromycin is an additional antibacterial agent with anti inflammatory effects that may be beneficial for treating dry eye disease

  11. I think it would be best for you to call your vet and let them examine your dog Ibrahim AY, et al

  12. 061 mmol, 99 yield Hypomagnesemia has inhibitory effects on Na K ATPase and is refractory to K administration unless Mg is concurrently replenished

  13. The authors conclude that the production of basic fibroblast growth factor by mast cells may contribute to lung injury in silicosis Haywood, USA 2022 05 21 01 28 49

  14. How is UPJ obstruction treated Wu J, Li S, Yang Y, Zhu S, Zhang M, Qiao Y, Liu YJ, Chen J

  15. Chlamydial immunoglobulin IgG and IgA antibodies in serum and semen are not associated with the presence of Chlamydia trachomatis DNA or rRNA in semen from male partners of infertile couples

  16. Body weight was monitored weekly as an indicator of drug induced toxicity and overall health of the mice Major medications that work for the disease treatment are

  17. PSM of baseline demographic and clinical characteristics at a ratio of 1 1 then identified 464 patients in each treatment group

网站地图