f<Type>(arguments)
fn[T : Show] to_string(x : T) -> String {
Show::to_string(x)
}
test {
let a = to_string(1)
let b = to_string(false)
assert_eq(a, "1")
assert_eq(b, "false")
}fn[T : @string.FromStr] from_string(x : String) -> T {
try! @string.from_str(x)
}
fn f(_ : Int, _ : Bool) -> Unit {
...
}
test {
let a = from_string("123")
let b = from_string("false")
f(a, b)
}If inference is not available, add a type annotation to a let binding or
expression with : Type.test {
let a : Int = from_string("123")
let b = (from_string("false") : Bool)
assert_eq(a, 123)
assert_eq(b, false)
}fn[T : @string.FromStr] try_from_string(x : String) -> Result[T, Error] {
try! @string.from_str(x)
}
///|
#warnings("-partial_match")
test {
let Ok(a) : Result[Int, _] = try_from_string("123")
let Ok((b : Bool)) = try_from_string("false")
assert_eq(a, 123)
assert_eq(b, false)
}///|
trait TypeInfo {
fn name(@proxy.Proxy[Self]) -> String
}
///|
impl TypeInfo for Int with fn name(_) {
"Int"
}
///|
impl TypeInfo for Bool with fn name(_) {
"Bool"
}
///|
test {
let a = TypeInfo::name((Proxy : @proxy.Proxy[Int]))
let b = TypeInfo::name((Proxy : @proxy.Proxy[Bool]))
assert_eq(a, "Int")
assert_eq(b, "Bool")
}The trick is simple: pass the dummy value Proxy, which has a generic type, and
wrap it in a type annotation such as (expr : Proxy[Int]).f<Type>(arguments)