对我来说,这三门语言是作为主语言进行学习的,他们比较统一的特点是简单易上手,语法来说,Python写法简单易懂,其他两门类C语言虽然看起来不甚相同,其实也是殊途同归,这般相似有好处,也有不方便的地方,比如我在Subline写TS的时候已经忘了好几次for后面的括号了,,,
对比一下常用的语法不止是我的需求,我想也是很多接触过这三门语言的人的需要,话不多说,我们从一下几个方面开始,注意的是,本篇不涉及简单用法的使用说明和一些进阶用法,只是对比罗列而已。
注释
Python:
#
'''
code
'''
"""
code
"""
Go与TS:
//
/*
code
*/
变量赋值
Python: 最简单
a = 1
b = c = 2
d, e = 3, 4
Golang:
var a int
const a int = 1
a := 1
b := new(int)
var c string = '1' //wrong
var (
c int
d bool
f = [2] float64 {1,2}
)
const (
a = iota
b
)
var a map[string]int // panic: assignment to entry in nil map
var a = make(map[string]int)
TypeScript:
let a:number = 1;
const b:string = '1' ("2");
let c: boolean[] = [false, true];
类型
Python:类型转换时很方便
bool, int, float, str, list, tuple, dict, set
Golang
bool, int, float64, string, rune, byte, array, slice, map, struct, point, function, interface, channel
TypeScript
boolean, number, string, Array(tuple), enum, null, undefiend, symbol, void, any, never
类型转换
Py:
a = int(b)
so on...
Go:
var a int = 1
b := float64(a)
var c byte = 49
d := string(c)
e := strconv.Itoa(a)
f, _ := strconv.Atoi(d)
fmt.Println(b, e, f)
fmt.Println(d)
g, _ = strconv.ParseBool(e) //No int, e:
h = strconv.FormatBool(g)
i := new(int)
j := *i
k := &j
fmt.Println(i,j,k)
Ts:
let a number = 2;
let b string = String(a);
let c number = Number('123');
let d:boolean = Boolean(a);
//JS:
let e = 2;
let f = '1';
typeof(a+f);//string
typeof(a-f);//number
条件
Py:
if:
elif:
else:
Go:允许在if的表达式里定义变量
a:=12
switch {
case a>100:
fmt.Println('1')
case a>20:
fmt.Println('2')
case a>10:
fmt.Println('3')
}
//51
if contents, err := ioutil.ReadFile(filename); err != nil {
//if 可以赋值多个语句
fmt.Println(err)
} else {
fmt.Printf("%s\n", contents)
}
Ts:独有的三元表达式
if (){
}else if(){
}else{
}
switch(a){
case 1:
...
break;
}
c>120?console.log('yes'):console.log('no')
Loop
Py:
for i in range():
for num in nums:
while 1:
Go:不存在while
for i:=1;i<a;i++{
...
}
names := []string{"1", "2", "3"}
for i, n := range names {
fmt.Println(i,"+ 1 = " + n)
}
Ts,while和do-while略去
const person={1:"1",2:"2",3:"3"};
const apache:number[]=[1,2,3]
for (let y = 1;y<4;y++){
console.log(y)
}
for (let x in person)
{
console.log(person[x])
}
for (let y in p){
console.log(y)//0,1,2
}
for (let z of p){
console.log(z)//1,2,3
}
包引用
Py:
from a import b
Go:
import(
a "fmt"
)
classfunctionexport default
export interface StringValidator{
...
}
import * as S from "./StringValidator";
Other:
- Py:and or;
Go和Ts: && || - Py和Go不需要";",Ts需要,即使浏览器回为你加上。
- Py和Js中都可以使用""和''引出字符串,Go中''引出的是rune类型;同时除了Py之外,其他两门语言也可以用反引号表示字符串。
- 未完待续