Carbon条件语句 #

一、条件语句概述 #

条件语句用于根据条件执行不同的代码分支。Carbon提供了 if-else 语句和 match 模式匹配两种条件控制结构。

二、if语句 #

2.1 基本if语句 #

carbon
var score: i32 = 85;

if (score >= 60) {
  Print("及格");
}

2.2 if-else语句 #

carbon
var score: i32 = 45;

if (score >= 60) {
  Print("及格");
} else {
  Print("不及格");
}

2.3 if-else if-else链 #

carbon
var score: i32 = 85;

if (score >= 90) {
  Print("优秀");
} else if (score >= 80) {
  Print("良好");
} else if (score >= 70) {
  Print("中等");
} else if (score >= 60) {
  Print("及格");
} else {
  Print("不及格");
}

2.4 嵌套if语句 #

carbon
var age: i32 = 25;
var has_license: bool = true;

if (age >= 18) {
  if (has_license) {
    Print("可以驾驶");
  } else {
    Print("需要考取驾照");
  }
} else {
  Print("年龄不够");
}

三、条件表达式 #

3.1 if表达式 #

Carbon的if可以作为表达式使用:

carbon
var score: i32 = 85;
var result: String = if score >= 60 then "及格" else "不及格";
Print("{0}", result);

3.2 多分支表达式 #

carbon
var score: i32 = 85;
var grade: String = 
  if score >= 90 then "A"
  else if score >= 80 then "B"
  else if score >= 70 then "C"
  else if score >= 60 then "D"
  else "F";
Print("等级: {0}", grade);

3.3 块表达式 #

carbon
var x: i32 = 10;
var result: i32 = if x > 0 then {
  var doubled: i32 = x * 2;
  doubled
} else {
  0
};

四、match语句 #

4.1 基本match #

carbon
var day: i32 = 3;

match (day) {
  case 1 => Print("星期一");
  case 2 => Print("星期二");
  case 3 => Print("星期三");
  case 4 => Print("星期四");
  case 5 => Print("星期五");
  case 6 => Print("星期六");
  case 7 => Print("星期日");
  default => Print("无效的日期");
}

4.2 match表达式 #

carbon
var day: i32 = 3;
var name: String = match (day) {
  case 1 => "星期一";
  case 2 => "星期二";
  case 3 => "星期三";
  case 4 => "星期四";
  case 5 => "星期五";
  case 6 => "星期六";
  case 7 => "星期日";
  default => "无效";
};
Print("{0}", name);

4.3 多值匹配 #

carbon
var day: i32 = 6;

match (day) {
  case 1 or 2 or 3 or 4 or 5 => Print("工作日");
  case 6 or 7 => Print("周末");
  default => Print("无效");
}

4.4 范围匹配 #

carbon
var score: i32 = 85;

match (score) {
  case 90..100 => Print("优秀");
  case 80..89 => Print("良好");
  case 70..79 => Print("中等");
  case 60..69 => Print("及格");
  case 0..59 => Print("不及格");
  default => Print("无效分数");
}

五、模式匹配 #

5.1 变量绑定 #

carbon
var value: i32 = 42;

match (value) {
  case x if x > 100 => Print("大于100: {0}", x);
  case x if x > 50 => Print("大于50: {0}", x);
  case x => Print("其他: {0}", x);
}

5.2 元组匹配 #

carbon
var point: (i32, i32) = (10, 20);

match (point) {
  case (0, 0) => Print("原点");
  case (x, 0) => Print("X轴上: {0}", x);
  case (0, y) => Print("Y轴上: {0}", y);
  case (x, y) => Print("坐标: ({0}, {1})", x, y);
}

5.3 可选值匹配 #

carbon
var value: Optional(i32) = Some(42);

match (value) {
  case Some(x) => Print("值: {0}", x);
  case None => Print("无值");
}

5.4 类型匹配 #

carbon
interface Shape {
  fn Area(me) -> f64;
}

class Circle {
  var radius: f64;
  impl Shape {
    fn Area(me) -> f64 { return 3.14159 * me.radius * me.radius; }
  }
}

class Rectangle {
  var width: f64;
  var height: f64;
  impl Shape {
    fn Area(me) -> f64 { return me.width * me.height; }
  }
}

fn Describe(s: Shape) -> String {
  return match (s) {
    case c: Circle => "圆形,面积: {0}".Format(c.Area());
    case r: Rectangle => "矩形,面积: {0}".Format(r.Area());
  };
}

六、守卫条件 #

6.1 if守卫 #

carbon
var x: i32 = 15;

match (x) {
  case n if n < 0 => Print("负数");
  case n if n == 0 => Print("零");
  case n if n < 10 => Print("小于10的正数");
  case n if n < 100 => Print("两位数");
  default => Print("大于等于100");
}

6.2 复杂守卫 #

carbon
var age: i32 = 25;
var has_id: bool = true;

match ((age, has_id)) {
  case (a, true) if a >= 18 => Print("成年人,有证件");
  case (a, false) if a >= 18 => Print("成年人,无证件");
  case (_, _) => Print("未成年人");
}

七、实际应用 #

7.1 状态机 #

carbon
enum State {
  Idle,
  Running,
  Paused,
  Stopped
}

fn HandleEvent(state: State, event: Event) -> State {
  return match ((state, event)) {
    case (State.Idle, Event.Start) => State.Running;
    case (State.Running, Event.Pause) => State.Paused;
    case (State.Running, Event.Stop) => State.Stopped;
    case (State.Paused, Event.Resume) => State.Running;
    case (State.Paused, Event.Stop) => State.Stopped;
    case (s, _) => s;  // 保持当前状态
  };
}

7.2 错误处理 #

carbon
fn Divide(a: i32, b: i32) -> Optional(i32) {
  return if b == 0 then None else Some(a / b);
}

var result: Optional(i32) = Divide(10, 2);
match (result) {
  case Some(value) => Print("结果: {0}", value);
  case None => Print("除数不能为零");
}

7.3 命令解析 #

carbon
fn ParseCommand(cmd: String) -> Command {
  return match (cmd.ToLower()) {
    case "help" => Command.Help;
    case "exit" => Command.Exit;
    case "list" => Command.List;
    case s if s.StartsWith("get ") => Command.Get(s[4..]);
    case s if s.StartsWith("set ") => Command.Set(s[4..]);
    default => Command.Unknown(cmd);
  };
}

八、最佳实践 #

8.1 优先使用match #

carbon
// 推荐:使用match
match (status) {
  case 0 => Print("成功");
  case 1 => Print("失败");
  case 2 => Print("待处理");
  default => Print("未知状态");
}

// 不推荐:if-else链
if (status == 0) {
  Print("成功");
} else if (status == 1) {
  Print("失败");
} else if (status == 2) {
  Print("待处理");
} else {
  Print("未知状态");
}

8.2 确保穷尽性 #

carbon
// 好的做法:覆盖所有情况
enum Color { Red, Green, Blue }

fn ToHex(c: Color) -> String {
  return match (c) {
    case Color.Red => "#FF0000";
    case Color.Green => "#00FF00";
    case Color.Blue => "#0000FF";
  };
}

8.3 使用有意义的条件 #

carbon
// 好的做法
var is_valid: bool = age >= 18 and has_license;
if (is_valid) {
  Print("可以驾驶");
}

// 避免
if (age >= 18 and has_license) {
  Print("可以驾驶");
}

九、常见错误 #

9.1 遗漏default分支 #

carbon
var x: i32 = 100;
match (x) {
  case 1 => Print("一");
  case 2 => Print("二");
  // 遗漏default,x=100时无匹配
}

9.2 条件顺序错误 #

carbon
var score: i32 = 85;

// 错误:顺序不对
if (score >= 60) {
  Print("及格");
} else if (score >= 80) {  // 永远不会执行
  Print("良好");
}

// 正确:从高到低
if (score >= 80) {
  Print("良好");
} else if (score >= 60) {
  Print("及格");
}

9.3 赋值与比较混淆 #

carbon
var x: i32 = 10;

// 错误:使用赋值
// if (x = 10) { ... }

// 正确:使用比较
if (x == 10) {
  Print("等于10");
}

十、总结 #

本章我们学习了:

  1. if语句:基本if、if-else、if-else if-else
  2. 条件表达式:if作为表达式使用
  3. match语句:模式匹配、多值匹配
  4. 模式匹配:变量绑定、元组匹配、类型匹配
  5. 守卫条件:if守卫、复杂条件
  6. 最佳实践:优先使用match、确保穷尽性

接下来让我们学习Carbon的循环语句!

最后更新:2026-03-27