module Cast { 
 
  // CAST BASICS 
 
  // use x::t to cast a value x to another type t 
  // use x::?t to see if a cast is possible (evaluates to true or false) 
 
  fn test1() { 
    let x : int = 1;     
 
    let y = x::u16;   // cast x to u16 type 
 
    if (x::?u8) {     // check if value can be cast to u8 
      let z = y::u8;  // cast to u8 
    } 
  } 
 
  // INTERFACE CASTS 
 
  // to obtain an interface for a type, cast to the interface type 
  // see interfaces for more info 
 
  // define Pet interface 
  interface Pet { 
    name.get() : string;  // get property name  
  } 
 
  // define Cat structure 
  struct Cat { 
    name : string; 
  } 
 
  // define Dog structure 
  struct Dog { 
    name : string; 
  } 
 
  // implement Pet interface for Cat and Dog 
  impl Pet { 
    name.get(this : Cat) : string => { 
      return this.name; 
    } 
 
    name.get(this : Dog) : string => { 
      return this.name; 
    } 
  } 
 
  fn test2() { 
    let cat = Cat("paws"); 
    let dog = Dog("fido"); 
 
    let cat_pet = cat::Pet; // get Pet interface for Cat 
    let dog_pet = dog::Pet; // get Pet interface for Dog 
 
    print(cat_pet.name);    // prints paws 
    print(dog_pet.name);    // prints fido 
  } 
 
  // POLYMORPHIC INTERFACE CASTS 
 
  // casting a union to an interface will return the interface  
  // for the value in the union.  this is a way to obtain an  
  // interface polymorphically.   
 
  fn test3() { 
    let animals = [Cat("paws"), Dog("fido")]; 
 
    for (animal in animals) { 
      let pet = animal::Pet; 
      print(pet.name);        // prints pawsfido 
    } 
  } 
 
  // CHECKING FOR INTERFACES 
 
  // if the type in the union does not support the interface 
  // being cast to, then an exception will be thrown.   
  // 
  // the ::? operator can be used to check if the interface  
  // is supported. 
 
  // Tiger does not implement Pet 
  struct Tiger {} 
 
  fn test4() { 
    let animals = [Cat("paws"), Dog("fido"), Tiger]; 
 
    for (animal in animals) { 
 
      // check if animal supports Pet interface 
      if (animal::?Pet) { 
 
        let pet = animal::Pet; 
        print(pet.name);          // prints pawsfido 
      } 
    } 
  } 
 
 
 
}