Golang与JAVA比较
source link: https://studygolang.com/articles/17805?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
普通用法比较
函数
func swap(x, y string) (string, string) {
var a int = 100
return y, x
}
a, b := swap("Mahesh", "Kumar")
go的方法需要加func
入参类型在参数后面,返回类型在入参后面
定义类型在变量的后面
返回值可以是多个参数
函数定义后可作为值来使用
java 中的null go中的nil
go中的数组var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}
go &a a的地址
var ip *int
java的class就是go的struct
java中get,set方法
Book1.title = "Go 语言"
fmt.Printf( "Book 1 title : %s\n", Book1.title)
结构体指针
切片就是java中的list
var numbers []int
numbers = append(numbers, 2,3,4)
copy(numbers1,numbers)
for循环
for _, num := range nums {
sum += num
}
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
map用法:
var countryCapitalMap map[string]string /*创建集合 */
countryCapitalMap = make(map[string]string)
/* map插入key - value对,各个国家对应的首都 */
countryCapitalMap [ "France" ] = "Paris"
delete(countryCapitalMap, "France")
for country := range countryCapitalMap {
fmt.Println(country, "首都是", countryCapitalMap [country])
}
强制转化int,string
#string到int
int,err:=strconv.Atoi(string)
#string到int64
int64, err := strconv.ParseInt(string, 10, 64)
#int到string
string:=strconv.Itoa(int)
#int64到string
string:=strconv.FormatInt(int64,10)
Go 并发
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
通道(channel)
ch <- v // 把 v 发送到通道 ch
v := <-ch // 从 ch 接收数据
// 并把值赋给 v
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // 从通道 c 中接收
通道可以设置缓冲区,通过 make 的第二个参数指定缓冲区大小:
ch := make(chan int, 100)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
// range 函数遍历每个从通道接收到的数据,因为 c 在发送完 10 个
// 数据之后就关闭了通道,所以这里我们 range 函数在接收到 10 个数据
// 之后就结束了。如果上面的 c 通道不关闭,那么 range 函数就不
// 会结束,从而在接收第 11 个数据的时候就阻塞了。
for i := range c {
fmt.Println(i)
}
并发线程模型比较
在解决高并发的时候,go相对于java来说是省去了公用内存这一步改成了1对1传值通信。
Java线程模型
Go的线程实现模型
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK