switch
PHP
switch ($i) {
case0:
// something to do
break;
case 1:
case 2:
case 3:
// something to do
break;
default:
// something to do
}
18.
Go
switch $i {
case0:
// something to do
case 1, 2, 3:
// something to do
default:
// something to do
}
breakを書かなくてもデフォルトでbreakする
複数の値を条件とするときはまとめることができる
意図的に他のcaseを実行したいときは fallthrough を使う
19.
関数
返り値が1つ
PHP
function max(int $a,int $b) : int {
if ($a > $b) {
return $a;
}
return $b
}
Go
func max(a, b int) int {
if a > b {
return a
}
return b
}
可変長引数
PHP
function count(int ...$numbers){
foreach ($numbers as $number) {
echo($number);
}
}
Go
func count(numbers ...int) {
for _, number := range numbers {
fmt.Printf(number)
}
構造体
構造体の宣言
PHP
構造体という概念がないのでクラスで代替
class Person {
private$name;
private $age;
function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
// getter省略
}
$man = new Person("Sawaya", 23);
echo("I am ", $man->getName());
echo("My age is ", $man->getAge());
25.
Go
type person struct{
name string
age int
}
var man person
man.name = "sawaya"
man.age = 23
fmt.Println("I am ", man.name)
fmt.Println("My age is ", man.age)
26.
メソッド
構造体という概念がないのでクラスで代替
PHP
class Rectangle {
private$width;
private $height;
public function __construct(
float $width, float $height)
{
$this->width = $width;
$this->height = $height;
}
private function area() : float {
return $this->width * $this->height;
}
// getter省略
}
$square = new Rectangle(12, 2);
echo("Area of Square is: ", $square->area());
27.
Go
type Rectangle struct{
width, height float64
}
func (r Rectangle) area() float64 {
return r.width * r.height
}
square := Rectangle{12, 2}
fmt.Println("Area of Square is: ", square.area())