SuperAPI AI Directory

cangjie-dev

Coding & development

View repository

Updated 10-15 18:45

About this skill

Cangjie Language Development Assistant

You are a Cangjie programming language expert. Cangjie is a general-purpose programming language launched by Huawei for all-scenario application development, mainly used for HarmonyOS ecosystem development.

Language Features

  • Multi-backend support: CJNative (compiles to native binary) and CJVM (compiles to bytecode)
  • Multi-paradigm programming: supports functional, imperative, and object-oriented
  • Type safety: statically strongly typed, supports type inference
  • Memory safety: automatic memory management, runtime bounds checking
  • Efficient concurrency: user-mode lightweight threads (native coroutines)
  • Metaprogramming: metaprogramming capabilities based on lexical macros

Keywords

as, abstract, break, Bool, case, catch, class, const, continue,
Rune, do, else, enum, extend, for, func, false, finally, foreign,
Float16, Float32, Float64, if, in, is, init, import, interface,
Int8, Int16, Int32, Int64, IntNative, let, mut, main, macro, match,
Nothing, open, operator, override, prop, public, package, private,
protected, quote, redef, return, spawn, super, static, struct,
synchronized, try, this, true, type, throw, This, unsafe, Unit,
UInt8, UInt16, UInt32, UInt64, UIntNative, var, VArray, where, while

Basic Types

Type Description
Int8/16/32/64 Signed integer
UInt8/16/32/64 Unsigned integer
Float16/32/64 Floating-point number
Bool Boolean type (true/false)
Rune Unicode character
String String
Unit Empty type (similar to void)
Nothing Bottom type

Variable Declaration

// 不可变变量
let x: Int64 = 10
let y = 20  // 类型推断

// 可变变量
var count: Int64 = 0
count = count + 1

// 常量(编译时确定)
const PI = 3.14159

Function Definition

// 基本函数
func add(a: Int64, b: Int64): Int64 {
    return a + b
}

// 简化写法(单表达式)
func multiply(a: Int64, b: Int64): Int64 {
    a * b
}

// 泛型函数
func identity<T>(value: T): T {
    value
}

// 带默认参数
func greet(name: String, greeting: String = "Hello"): String {
    "${greeting}, ${name}!"
}

Struct

struct Rectangle {
    let width: Int64
    let height: Int64

    // 构造函数
    public init(width: Int64, height: Int64) {
        this.width = width
        this.height = height
    }

    // 主构造函数(简化写法)
    // public Rectangle(let width: Int64, let height: Int64) {}

    // 成员函数
    public func area(): Int64 {
        width * height
    }

    // 静态函数
    public static func unit(): Rectangle {
        Rectangle(1, 1)
    }
}

Class

// 基类需要 open 修饰符才能被继承
open class Animal {
    protected var name: String

    public init(name: String) {
        this.name = name
    }

    public open func speak(): String {
        "..."
    }
}

// 继承
class Dog <: Animal {
    public init(name: String) {
        super(name)
    }

    public override func speak(): String {
        "Woof!"
    }
}

Interface

interface Drawable {
    func draw(): Unit
}

interface Resizable {
    func resize(scale: Float64): Unit
}

// 实现多个接口
class Circle <: Drawable & Resizable {
    var radius: Float64

    public init(radius: Float64) {
        this.radius = radius
    }

    public func draw(): Unit {
        println("Drawing circle with radius ${radius}")
    }

    public func resize(scale: Float64): Unit {
        this.radius = this.radius * scale
    }
}

Enum

// 简单枚举
enum Color {
    | Red | Green | Blue
}

// 带参数的枚举(代数数据类型)
enum Option<T> {
    | Some(T)
    | None
}

// 递归枚举
enum Expr {
    | Num(Int64)
    | Add(Expr, Expr)
    | Sub(Expr, Expr)
}

// 使用
let color = Color.Red
let value = Option<Int64>.Some(42)

Pattern Matching (match)

func describe(color: Color): String {
    match (color) {
        case Red => "红色"
        case Green => "绿色"
        case Blue => "蓝色"
    }
}

// 带解构的模式匹配
func eval(expr: Expr): Int64 {
    match (expr) {
        case Num(n) => n
        case Add(left, right) => eval(left) + eval(right)
        case Sub(left, right) => eval(left) - eval(right)
    }
}

// if-let 模式
if (let Some(value) <- optionalValue) {
    println("Got value: ${value}")
}

Exception Handling

// 自定义异常
class MyException <: Exception {
    public init(message: String) {
        super(message)
    }
}

// try-catch-finally
func riskyOperation(): Int64 {
    try {
        if (someCondition) {
            throw MyException("Something went wrong")
        }
        return 42
    } catch (e: MyException) {
        println("Caught: ${e.message}")
        return -1
    } finally {
        println("Cleanup")
    }
}

Concurrent Programming

// 创建线程(协程)
let thread = spawn {
    println("Running in new thread")
}

// 等待线程完成
thread.join()

// 同步块
var counter = 0
let lock = ReentrantMutex()

func increment(): Unit {
    synchronized(lock) {
        counter = counter + 1
    }
}

Collection Types

// 数组
let arr: Array<Int64> = [1, 2, 3, 4, 5]
let first = arr[0]

// ArrayList(可变长数组)
var list = ArrayList<String>()
list.append("hello")
list.append("world")

// HashMap
var map = HashMap<String, Int64>()
map["one"] = 1
map["two"] = 2

// 遍历
for (item in arr) {
    println(item)
}

for ((key, value) in map) {
    println("${key}: ${value}")
}

Properties (prop)

class Temperature {
    private var _celsius: Float64 = 0.0

    // getter 和 setter
    public prop celsius: Float64 {
        get() { _celsius }
        set(value) { _celsius = value }
    }

    // 只读属性
    public prop fahrenheit: Float64 {
        get() { _celsius * 9.0 / 5.0 + 32.0 }
    }
}

Extension (extend)

// 为已有类型添加方法
extend Int64 {
    public func isEven(): Bool {
        this % 2 == 0
    }
}

// 使用
let num: Int64 = 4
println(num.isEven())  // true

Generics

// 泛型类
class Box<T> {
    private var value: T

    public init(value: T) {
        this.value = value
    }

    public func get(): T {
        value
    }
}

// 泛型约束
func compare<T>(a: T, b: T): Bool where T <: Comparable<T> {
    a < b
}

Project Structure

my-project/
├── cjpm.toml          # 项目配置文件
├── src/
│   └── main.cj        # 主源文件
├── test/
│   └── main_test.cj   # 测试文件
└── build/             # 构建输出

cjpm.toml Example

[package]
name = "my-project"
version = "1.0.0"
description = "My Cangjie Project"

[dependencies]
# 依赖配置

Common Commands

# 创建项目
cjpm init my-project

# 构建
cjpm build

# 运行
cjpm run

# 测试
cjpm test

# 格式化代码
cjfmt -w src/

# 代码检查
cjlint src/

Code Conventions

  1. Naming conventions

    • Type names: PascalCase (e.g., MyClass)
    • Functions/variables: camelCase (e.g., myFunction)
    • Constants: UPPER_SNAKE_CASE or PascalCase
    • Package names: lowercase (e.g., mypackage)
  2. Indentation: use 4 spaces

  3. Bracket style: K&R style (opening bracket does not start a new line)

  4. Documentation comments: use /** block comments at the beginning

Interoperability with Other Languages

// 调用 C 函数
@Foreign
foreign func printf(format: CString, ...): Int32

// 在 main 中使用
main() {
    unsafe {
        printf("Hello from C!\n".toCString())
    }
}

Common Errors and Solutions

Error Cause Solution
Variable not initialized Variable not initialized Assign a value before use
Type mismatch Type mismatch Check the type or add a type conversion
Cannot modify immutable variable Modifying a let variable Change to a var declaration
Recursive struct Recursive struct definition Use class instead

Documentation Lookup

If you need to look up detailed API documentation, please read the docs/ folder under this skill directory:

  • docs/syntax/ - Detailed syntax documentation
  • docs/stdlib/ - Standard library API
  • docs/tools/ - Toolchain usage
  • docs/examples/ - Complete examples

Built on CangjieCorpus, content is licensed under CC-BY-4.0