Generics and type inference · Coding Class
This topic is not available in the selected language or version. Showing the start of this section.
Apply the chapter in three steps: an exercise, a program project, and a debugging task. Implement first, then consult the hints and completion criteria. Use a separate file or working directory for each task.
1. Exercise · Choose type arguments
Section titled “1. Exercise · Choose type arguments”Call identity with Int, String, and identity<I32>(1); store each result in a variable of the corresponding type.
Completion: Print 7, hello, 1 and explain T for all three calls.
Hint: Infer from arguments or supply the full type argument list.
2. Build a program · Reuse a fallback selector
Section titled “2. Build a program · Reuse a fallback selector”Use or_default<T> for Option<Int> and Option<String>: Some(5), Int None, Some(“x”), and String None, with fallbacks 0 and untitled.
Completion: Output is 5, 0, x, untitled, using one generic function without arithmetic.
Hint: Match the known shape of Option<T>.
3. Debug · Fix receiving-type inference
Section titled “3. Debug · Fix receiving-type inference”Fix the mismatch below in two ways: an explicit type argument and conversion of the argument. Keep the result variable typed I32.
Start with this deliberately broken program.
fn identity<T>(value: T) -> T { return value; }fn main() { let value: I32 = identity(1); println(value); }xen check class_inference.xenDiagnostic excerpt:
expected I32, found Int (I64)Completion: Both versions print 1 and check successfully.
Hint: Use identity<I32>(1) or identity(i32(1)).
Verify and record
Section titled “Verify and record”Use xen check file.xen followed by xen run file.xen for ordinary programs; use xen test file.xen for test-only files. Record the original error, its cause, and the corrected result, then rerun every input in the completion criteria.