Type Inference
Objective: Show how types are infered in different types of statements.
Python
Check types by calling: mypy --strict inference.py
def foo(x: int, y: int) -> int:
return x + y
class C:
def __init__(self, x: int):
self.x = x
def get_x(self) -> int:
return self.x
foo(2, 3)
c = C(123)
print(c.get_x())
Rust
fn foo(x : i32, y : i32) -> i32 { x + y } struct C { x : i32 } impl C { fn new(x : i32) -> Self { Self{x} } fn get_x(&self) -> i32 { self.x } } fn main() { println!("{:?}", foo(2, 3)); let c = C::new(123); println!("{:?}", c.get_x()); }
Crystal
# generic function
def foo(x, y)
x + y
end
class C
# type needs to be specified
def initialize(@x : Int32)
end
# type is inferred
def get_x
@x
end
end
puts foo(2, 3) # calls foo<Int32, Int32>:Int32
puts foo("hello", "world") # calls foo<String, String>:String
c = C.new(123)
puts c.get_x