Golang: 访问控制、if else、方法变量
侧边栏壁纸
  • 累计撰写 20 篇文章
  • 累计收到 1 条评论

Golang: 访问控制、if else、方法变量

admin
2022-07-17 / 0 评论 / 130 阅读
Go不像其他语言一样拥有 访问控制修饰符,如 privateprotectedpublic

Go 通过字母大小写下划线开头控制可见性

  • 大写字母开头 能被其他包访问或调用,相当于公开(public)的变量
  • 小写字母开头 只能在包内使用,相当于私有(private)变量

if else

  • 跟其他语言没什么区别,但是不需要圆括号
  • 在条件语句之前可以有一个声明语句;在这里声明的变量可以在这个语句所有的条件分支中使用。示例

    if num := 9; num < 0 {}

方法变量 示例

printType := func(i interface{}) {
        switch t := i.(type) {
        case bool:
            fmt.Println("is bool")
        case string:
            fmt.Println("is string")
        case int:
            fmt.Println("is int")
        case float32:
            fmt.Println("is float32")
        default:
            fmt.Printf("unknown type %T", t)
        }
    }

    printType(1)
    printType(false)
    printType(float32(1145141919.81))
    printType("this is a string")
    printType(float64(114514))

l5p3d27h.png

0

评论

博主关闭了所有页面的评论