X语言是一种现代、安全、高效的编程语言,设计目标是提供一种既具有高级语言表达能力,又具有接近低级语言性能的编程体验。
X语言的关键字包括:
fn let mut const struct enum if else for while match return import export module use type trait impl self super pub priv async await try catch throw option result
标识符由字母、数字和下划线组成,必须以字母或下划线开头。X语言区分大小写。
// 有效的标识符let x = 5;let _value = "hello";let userName = "John"; // 无效的标识符let 123abc = 10; // 不能以数字开头let my-variable = 20; // 不能包含连字符
bool - 布尔值(true 或 false)u8, u16, u32, u64, u128 - 无符号整数i8, i16, i32, i64, i128 - 有符号整数f32, f64 - 浮点数char - 字符string - 字符串array - 固定大小的数组list - 可变大小的列表map - 键值对映射set - 无序集合tuple - 元组struct - 结构体enum - 枚举trait - 特质(接口)// 不可变变量let x :i32 = 5; // 可变变量let mut y = 10;y = 15; // 允许修改 // 常量const PI :f64 = 3.14159;
fn add (a :i32 ,b :i32 ) ->i32 {return a +b ; } // 简短函数语法fn subtract (a :i32 ,b :i32 ) ->i32 =a -b ;
// if-else 语句if x > 0 {else if x < 0 {else {for i in 0..10 {i ); } // while 循环let mut i = 0;while i < 10 {i );i += 1; } // match 语句match x { 1 =>
// 结构体定义struct Person {name :string ,age :u32 , } // 枚举定义enum Option <T > {Some (T ),None , }
// 模块定义module utils {pub fn add (a :i32 ,b :i32 ) ->i32 {return a +b ; } } // 导入模块import utils ; // 使用模块中的函数let result =utils ::add (1, 2);
// 特质定义trait Drawable {fn draw (&self ); } // 实现特质struct Circle {radius :f64 , }impl Drawable for Circle {fn draw (&self ) {self .radius ); } }
// Option 类型fn divide (a :f64 ,b :f64 ) ->Option <f64 > {if b == 0.0 {return None ; }return Some (a /b ); } // Result 类型fn read_file (path :string ) ->Result <string ,string > { // 模拟文件读取if path == "nonexistent.txt" {return Err ("File not found".to_string()); }return Ok ("File content".to_string()); }