codecamp

hack类型别名:Transparent

transparent (透明)类型别名是一个使用创建的type

<?hh 
type  UserIDtoFriendIDsMap  =  Map < int , Vector < int >> ;

对于给定的类型,该类型和所有类型的透明别名都是相同的类型,并且可以自由交换 - 它们在所有方面完全相同。对于何处可以定义透明类型别名或哪些源代码可以访问其底层实现没有限制。

opaque类型别名不同,由于没有区别别名和别名类型,所以透明类型别名作为抽象机制并不是特别有用。他们的主要用例是定义一个简写类型的名字,增加可读性并且保存输入。考虑下面的函数签名,以及没有Matrix类型别名的话会有多麻烦:

<?hh

namespace Hack\UserDocumentation\TypeAliases\Transparent\Examples\Converted;

type Matrix<T> = Vector<Vector<T>>;

function add<T as num>(Matrix<T> $m1, Matrix<T> $m2): Matrix<num> {
  // Assumes that $m1 and $m2 have the same dimensions; real code should have
  // better error detection and handling of course.
  $r = Vector {};
  foreach ($m1 as $i => $row1) {
    $new_row = Vector {};
    foreach ($row1 as $j => $val1) {
      $new_row[] = $val1 + $m2[$i][$j];
    }
    $r[] = $new_row;
  }

  return $r;
}

function get_m1(): Matrix<int> {
  // No conversion needed from these Vectors into the Matrix return type, since
  // the two are equivalent.
  return Vector { Vector { 1, 2 }, Vector { 3, 4 } };
}

function get_m2(): Vector<Vector<int>> {
  return Vector { Vector { 5, 6 }, Vector { 7, 8 } };
}

function run(): void {
  var_dump(add(
    get_m1(),
    // get_m2() returns a Vector<Vector<int>>, and add() takes a Matrix<int>,
    // but no conversion is needed here since the two are equivalent.
    get_m2()
  ));
}

run();

Output

object(HH\Vector)#7 (2) {
  [0]=>
  object(HH\Vector)#8 (2) {
    [0]=>
    int(6)
    [1]=>
    int(8)
  }
  [1]=>
  object(HH\Vector)#9 (2) {
    [0]=>
    int(10)
    [1]=>
    int(12)
  }
}
hack类型别名:Opaque
hack类型别名示例
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }