Go 是由 Google 设计的一门静态类型的编译型语言。它有点类似于 C,但是它包含了更多的优点,比如垃圾回收、内存安全、结构类型和并发性。它的并发机制使多核和网络机器能够发挥最大的作用。这是 GoLang 的最佳卖点之一。此外,Go 速度快,表现力强,干净且高效。这也是 Go 如此吸引开发者学习的原因。

PHP 是一种动态类型语言,它使新手更容易编写代码。现在的问题是,PHP 开发人员能否从动态类型语言切换到像 Go 这样的静态类型语言?为了找到答案,让我们对比一下 Go 和 PHP 之间的语法差异。

八重樱:怎么从一名码农成为架构师的必看知识点:目录大全(不定期更新)​zhuanlan.zhihu.com

数据类型

  • Go 同时支持有符号和无符号整数,而 PHP 只支持有符号整数。
  • 另一个主要区别是数组。Go 对 array 和 map 有单独的类型,而 PHP 数组实际上是有序的 map。
  • Go 与 PHP 相比没有对象。但是,Go 有一个类似于 object 的 struct 类型。

PHP 数据类型:

boolean
string
integer // Signed integer, PHP does not support unsigned integers.
float (also known as "floats", "doubles", or "real numbers")
array
object
null
resource

Go 数据类型:

string
bool
int int8 int16 int32 int64 // Signed integer
uint uint8 uint16 uint32 uint64 uintptr // Unsigned integers
byte // alias for uint8
rune // alias for int32
float32 float64
complex64 complex128
array
slices
map
struct

变量

Go 使用 var 声明全局变量和函数变量。但是,它也支持带有初始化程序的简写语法,但只能在函数内部使用。另一方面,PHP 仅支持带有初始化程序的变量声明。

// 变量声明
// Go // PHP
var i int $i = 0 // integer
var f float64 $f = 0.0 // float
var b bool $b = false // boolean
var s string $s = "" // string
var a [2]string $a = [] // array
// 简短的变量声明
// Go // PHP
i := 0 $i = 0 // integer
f := 0.0 $f = 0.0 // float
b := false $b = false // boolean
s := "" $s = "" // string
a := [1]string{"hello"} $a = [] // array

类型转换

// Go
i := 42 // Signed integer
f := float64(i) // Float
u := uint(f) // Unsigned integer
// PHP
$i = 1;
$f = (float) $i; // 1.0
$b = (bool) $f // true
$s = (string) $b // "1"

数组

// Go
var a [2]string
a[0] = "Hello"
a[1] = "World"
// OR
a := [2]string{"hello", "world"}
// PHP
$a = [
"hello",
"world"
];

Maps

// Go
m := map[string]string{
"first_name": "Foo",
"last_name": "Bar",
}
// PHP
$m = [
"first_name" => "Foo",
"last_name" => "Bar"
];

对象类型

Go 不支持对象。但是,您可以使用 structs 实现 object 之类的语法。

// Go
package main
import "fmt"
type Person struct {
Name string
Address string
}
func main() {
person := Person{"Foo bar", "Sydney, Australia"}
fmt.Println(person.Name)
}
// PHP
$person = new stdClass;
$person->Name = "Foo bar";
$person->Address = "Sydney, Australia";
echo $person->Name;
// 或使用类型转换
$person = (object) [
'Name' => "Foo bar",
'Address' => "Sydney, Australia"
];
echo $person->Name;

函数

Go 和 PHP 函数之间的主要区别是; Go 函数可以返回任意数量的结果,而 PHP 函数只能返回一个结果。但是,PHP 可以通过返回数组来模拟相同的功能。

// Go
package main
import "fmt"
func fullname(firstName string, lastName string) (string) {
return firstName + " " + lastName
}
func main() {
name := fullname("Foo", "Bar")
fmt.Println(name)
}
// PHP
function fullname(string $firstName, string $lastName) : string {
return $firstName . " " . $lastName;
}
$name = fullname("Foo", "Bar");
echo $name; // 返回多个结果
// Go
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
// PHP
// 返回一个数组以获得多个结果
function swap(string $x, string $y): array {
return [$y, $x];
}
[$a, $b] = swap('hello', 'world');
echo $a, $b;

控制语句

If-Else

// Go
package main
import (
"fmt"
)
func compare(a int, b int) {
if a > b {
fmt.Println("a is bigger than b")
} else {
fmt.Println("a is NOT greater than b")
}
}
func main() {
compare(12, 10);
}
// PHP
function compare(int $a, int $b) {
if ($a > $b) {
echo "a is bigger than b";
} else {
echo "a is NOT greater than b";
}
}
compare(12, 10);

Switch

根据 Golang 官方教程文档:

Go 的 switch 与 C,C+,Java,JavaScript 和 PHP 中的类似,除了 Go 只运行选中的 case,而不是随后的所有 case。 实际上, break 语句在这些语言中的每个 case 后都是必需的,而在 Go 中则是自动补充的。另一个重要的区别是 Go 的 switch cases 不需要是常量,并且涉及的值也不必是整数。

// Go
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ") os := runtime.GOOS; switch os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.\n", os)
}
}
// PHP
echo "PHP runs on "; switch (PHP_OS) {
case "darwin":
echo "OS X.";
break;
case "linux":
echo "Linux.";
break;
default:
echo PHP_OS;
}

For 循环

// Go
package main
import "fmt"
func main() {
sum := 0 for i := 0; i < 10; i++ {
sum += i
} fmt.Println(sum)
}
// PHP
$sum = 0; for ($i = 0; $i < 10; $i++) {
$sum += $i;
}
echo $sum;

While 循环

Go 自身没有 while 循环的语法。相应的,Go 使用 for 循环代替实现 while 循环.

// Go
package main
import "fmt"
func main() {
sum := 1 for sum < 100 {
sum += sum
} fmt.Println(sum)
}
// PHP
$sum = 1;
while ($sum < 100) {
$sum += $sum;
}
echo $sum;

Foreach/Range

PHP 使用 foreach 迭代数组和对象。与之对应,Go 使用 range 迭代 slice 或 map。

// Go
package main
import "fmt"
func main() {
colours := []string{"Maroon", "Red", "Green", "Blue"} for index, colour := range colours {
fmt.Printf("index: %d, colour: %s\n", index, colour)
}
}
// PHP
$colours = ["Maroon", "Red", "Green", "Blue"]; foreach($colours as $index => $colour) {
echo "index: {$index}, colour: {$colour}\n";
}

今天的内容就是这些。我尽量使文章篇幅较小且简洁。作为 PHP 开发人员, 我尝试在练习 Go 时分享我的知识。也请随意分享你的想法。希望你们喜欢阅读本篇文章。

八重樱:怎么从一名码农成为架构师的必看知识点:目录大全(不定期更新)​zhuanlan.zhihu.com

Go 与 PHP 的语法对比的更多相关文章

  1. Java, C#, Swift语法对比速查表

    原文:Java, C#, Swift语法对比速查表   Java 8 C# 6 Swift 变量 类型 变量名; 类型 变量名; var 变量名 : 类型; 变量(类型推断) N/A var 变量名= ...

  2. Python3 与 C# 面向对象之~继承与多态 Python3 与 C# 面向对象之~封装 Python3 与 NetCore 基础语法对比(Function专栏) [C#]C#时间日期操作 [C#]C#中字符串的操作 [ASP.NET]NTKO插件使用常见问题 我对C#的认知。

    Python3 与 C# 面向对象之-继承与多态   文章汇总:https://www.cnblogs.com/dotnetcrazy/p/9160514.html 目录: 2.继承 ¶ 2.1.单继 ...

  3. MongoDB命令及SQL语法对比

    mongodb与mysql命令对比 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(col ...

  4. MongoDB(五)mongo语法和mysql语法对比学习

    我们总是在对比中看到自己的优点和缺点,对于mongodb来说也是一样,对比学习让我们尽快的掌握关于mongodb的基础知识. mongodb与MySQL命令对比 关系型数据库一般是由数据库(datab ...

  5. Python3 与 C# 基础语法对比(String专栏)

      Code:https://github.com/lotapp/BaseCode 多图旧排版:https://www.cnblogs.com/dunitian/p/9119986.html 在线编程 ...

  6. Python3 与 C# 基础语法对比(List、Tuple、Dict、Set专栏)

      Code:https://github.com/lotapp/BaseCode 多图旧版:https://www.cnblogs.com/dunitian/p/9156097.html 在线预览: ...

  7. Python3 与 C# 基础语法对比(Function专栏)

      Code:https://github.com/lotapp/BaseCode 多图旧版:https://www.cnblogs.com/dunitian/p/9186561.html 在线编程: ...

  8. Python3 与 NetCore 基础语法对比(Function专栏)

    Jupyter最新排版:https://www.cnblogs.com/dotnetcrazy/p/9175950.html 昨晚开始写大纲做demo,今天牺牲中午休息时间码文一篇,希望大家点点赞 O ...

  9. Python3 与 NetCore 基础语法对比(String专栏)

    汇总系列:https://www.cnblogs.com/dunitian/p/4822808.html#ai Jupyter排版:https://www.cnblogs.com/dunitian/p ...

  10. Python学习笔记:与Java 基础语法对比

    闲着无聊学习下Python 的语法.由于我目前主要编程语言还是Java ,所以针对Python 的学习我主要是通过与Java 进行对比.我使用的是Python3,因此语法上也会遵循Python3 的规 ...

随机推荐

  1. springBoot 启动没有数据库配置报错

    在没有配置数据库的时候, 直接启动springBoot 项目 会有报错 Description: Failed to configure a DataSource: 'url' attribute i ...

  2. git上传本地代码到远程失败

    出现这种错误的原因是由于我不小心勾选了这个

  3. WTL改变对话框大小

    1.让对话框从CdialogResize类继承过来: class CMainDlg : public CDialogImpl<CMainDlg>, public CDoubleBuffer ...

  4. FFMPEG学习----使用SDL播放PCM数据

    参考雷神的代码: /** * 最简单的SDL2播放音频的例子(SDL2播放PCM) * Simplest Audio Play SDL2 (SDL2 play PCM) * * 本程序使用SDL2播放 ...

  5. PAT_B_PRAC_1003养兔子

    题目描述 一只成熟的兔子每天能产下一胎兔子.每只小兔子的成熟期是一天. 某人领养了一只小兔子,请问第N天以后,他将会得到多少只兔子. 输入描述: 测试数据包括多组,每组一行,为整数n(1≤n≤90). ...

  6. remote: error: hook declined to update refs/heads

    打开工程目录下.git/config文件,补充user信息 , [user] username = xxx email = xxx@126.com 打开工程目录下.git/description文件, ...

  7. GBM,XGBoost,LightGBM

    GBM如何调参:https://www.analyticsvidhya.com/blog/2016/02/complete-guide-parameter-tuning-gradient-boosti ...

  8. Asp.Net Core IdentityServer4 管理面板集成

    前言 IdentityServer4(以下简称 Id4) 是 Asp.Net Core 中一个非常流行的 OpenId Connect 和 OAuth 2.0 框架,可以轻松集成到 Asp.Net C ...

  9. Shiro自动登录

    Shiro RememberMe spring.xml <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager& ...

  10. MySQL :LAST_INSERT_ID()函数总结

    作用:当对table进行insert操作时,返回具有Auto_increment(自动增长)特性的属性列的最新值. 该函数的特点 1.每当断开本次连接之后又重新连接时,该函数的返回值会被重置为0. 2 ...