W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
transparent (透明)類型別名是一個(gè)使用創(chuàng)建的type。
<?hh
type UserIDtoFriendIDsMap = Map < int , Vector < int >> ;
對(duì)于給定的類型,該類型和所有類型的透明別名都是相同的類型,并且可以自由交換 - 它們?cè)谒蟹矫嫱耆嗤?duì)于何處可以定義透明類型別名或哪些源代碼可以訪問其底層實(shí)現(xiàn)沒有限制。
與opaque類型別名不同,由于沒有區(qū)別別名和別名類型,所以透明類型別名作為抽象機(jī)制并不是特別有用。他們的主要用例是定義一個(gè)簡寫類型的名字,增加可讀性并且保存輸入。考慮下面的函數(shù)簽名,以及沒有Matrix類型別名的話會(huì)有多麻煩:
<?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)
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: