代码改变世界

golang常见错误

2022-03-23 00:44  youxin  阅读(543)  评论(0编辑  收藏  举报
Go 报错:unexpected newline, expecting comma or }

答案
在多行切片,数组或映射文字中,每行必须以逗号结尾。

func main() {
fruit := []string{
"apple",
"banana",
"cherry", /添加了逗号
}
fmt.Println(fruit) // "[apple banana cherry]"
}
这种行为是 Go 分号插入规则的结果。

因此,您可以在不修改周围代码的情况下添加和删除行。

 

golang结构体命名大小写

 

结构体中如果字段名为小写,当做数据解析时无法访问(如json.mashal操作),则无法正确解析数据
  • 至于原因嘛,还是由于json.marshal()调用属于跨包调用,根据go语言变量命名的规则,如果是小写,则是私有变量,在包外而言,是不可见的。

 

go的结构体成员只有 可导出 的字段才会被 编码/解码。必须以大写字母开头的字段才是可导出的

1、golang的命名需要使用驼峰命名法,且不能出现下划线

2、golang中根据首字母的大小写来确定可以访问的权限。无论是方法名、常量、变量名还是结构体的名称,如果首字母大写,则可以被其他的包访问;如果首字母小写,则只能在本包中使

  可以简单的理解成,首字母大写是公有的,首字母小写是私有的

3、结构体中属性名的大写

如果属性名小写则在数据解析(如json解析,或将结构体作为请求或访问参数)时无法解析

type User struct {

        name string

        age  int

 }

func main() {

         user:=User{"Tom",18}

         if userJSON,err:=json.Marshal(user);err==nil{

           fmt.Println(string(userJSON))   //数据无法解析

        }

}

 

如上面的例子,如果结构体中的字段名为小写,则无法数据解析。所以一般建议结构体中的字段大写

————————————————

Golang If-Else Vs C If-Else

No Newline Block

if true
{
	fmt.Println("Hello World!")
}

OR

if true
{
	fmt.Println("Hello World!")
}
else
{
	fmt.Println("Else Block")
}

Syntax Error : – syntax error: unexpected newline, expecting { after if clause

The Correct Syntax for Golang if-else Statement is:

if true {
	fmt.Println("Hello World!")
}

OR

if true {
	fmt.Println("Hello World!")
} else {
	fmt.Println("Else Block")
}

Output- Hello World!

Golang If-Else Always Maintains Block

In other languages like C, C++, or Java, it is not necessary to define a block using ‘{‘ for a single statement. like:

C++ If-Else example:

if(true)
    std::cout<<"Hello World"<<std::endl;

But in Go, it is mandatory to put braces for a single line of statement too.

Golang If-else Example:

	if true
		fmt.Println("Hello World!")

Error: – syntax error: unexpected newline, expecting { after if clause

Golang If-Else Statement Initializer Syntax

if <Initializer> ; <Condition> { // Statement }

 

if ds, ok := csMarks["XYZ"]; ok {

fmt.Println(ds) }

else {

fmt.Println("Key Not Present in the Map") }

 

https://go101.org/article/line-break-rules.html