• 搜索
  • 夜间模式
    ©2012-2026  陈十一的小破站 Theme by OneBlog

    陈十一的小破站博客

    搜索
    标签
    # Nodejs # CentOS # Git # Golang # Docker # Windows # Nginx # 反向代理 # 脚本 # Linux
  • 首页>
  • 技术>
  • 正文
  • Golang居然没有三元运算符?

    2025年01月30日 717 阅读 0 评论 2156 字

    三元运算符在其他语言中的使用及 Golang 的取舍

    不同语言的三元运算符语法

    Python

    val = trueValue if expr else falseValue

    JavaScript

    const val = expr ? trueValue : falseValue

    C/C++

    const char *val = expr ? "trueValue" : "falseValue";

    Golang 的三元运算符缺失

    在 Golang 中尝试使用三元运算符会报错:

    val := expr ? "trueValue" : "falseValue" // 编译器报错:invalid character U+003F '?'

    官方解释

    The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

    核心观点:

    1. 复杂三元表达式会降低可读性
    2. if-else 结构更清晰
    3. 遵循"大道至简"设计哲学

    复杂三元表达式示例

    示例1:嵌套三元表达式

    const status = (type===1?(agagin===1?'再售':'已售'):'未售')

    示例2:多层级三元判断

    const word = (res.distance === 0) ? 'a'
        : (res.distance === 1 && res.difference > 3) ? 'b'
        : (res.distance === 2 && res.difference > 5 && String(res.key).length > 5) ? 'c'
        : 'd';

    转换为 if 语句的优化

    示例1 优化

    let status = '未售'
    if (type === 1) {
        status = again === 1 ? '再售' : '已售'
    }

    示例2 优化(使用 else-if 结构)

    let word = 'd'
    if (res.distance === 0) {
        word = 'a'
    } else if (res.distance === 1 && res.difference > 3) {
        word = 'b'
    } else if (res.distance === 2 && res.difference > 5 && String(res.key).length > 5) {
        word = 'c'
    }

    替代方案探讨

    函数模拟(不推荐)

    func If(cond bool, a, b interface{}) interface{} {
        if cond {
            return a
        }
        return b
    }
    
    val := If(age > 18, "成年人", "未成年人").(string)

    缺点:

    • 接口类型导致性能损失
    • 需要强制类型断言
    • 参数会立即求值(失去惰性计算特性)

    三元运算符的优缺点分析

    优点

    • 对简单表达式表意清晰
    • 支持常量赋值(可用 const 声明)
    • 无中间状态,副作用更少

    缺点

    • 复杂逻辑可读性差
    • 易被滥用替代合理控制流
    • 分支只能包含表达式

    参考链接

    • Golang 官方 FAQ
    • 替代嵌套三元运算符的方法
    • 深入理解 JS 中的条件语句
    本文著作权归作者 [ 陈十一 ] 享有,未经作者书面授权,禁止转载,封面图片来源于 [ 互联网 ] ,本文仅供个人学习、研究和欣赏使用。如有异议,请联系博主及时处理。
    Golang
    — END —
    Copyright©2012-2026  All Rights Reserved.  Load:0.012 s
    Theme by OneBlog V3.6.5
    夜间模式

    开源不易,请尊重作者版权,保留基本的版权信息。