本文摘自php中文网,作者V,侵删。

变量声明与赋值
Java:
Go:
1、变量声明:var是关键字,格式:var 变量名称 变量类型
2、变量声明与赋值: := 符号支持自动推导类型
异常处理
Java:

Go:

go的异常是做为函数返回值的,通过判断是否存在error,来判断异常。 (不能够像Java一样抛出异常)
go的if语句支持初始条件,即先执行if之后的语句(分号之前),再执行分号之后的判断语句,此语句经常用于异常处理。
go的大括号必须在行末go函数或者变量为”公有”,首字母大写,”私有”则小写。
参数传递

change函数是传递的对象,函数调用的时候,会拿到对象的拷贝。
change2函数是传递的指针,函数调用的时候,会拿到一个指向改对象的指针。
go没有引用传递
多态
此例有点长,是一个求面积的问题,针对与圆形和矩形两种类型
java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | java.lang.Math; public class Polymorphism{
public static class Rectangle implements Areable{
double height;
public Rectangle(double width,double height){
this.width = width;
this.height = height;}
public double area(){
return width * height;}
}
public static class Circle implements Areable{
public Circle(double radius){
this.radius = radius;}
public double area(){
return radius * radius * Math.PI;}
} public static interface Areable{
double area();
} public static void main(String[] args){
Areable arear = new Rectangle(5.0,5.0);
Areable areac = new Circle(2.5);
System.out.println(arear.area());
System.out.println(areac.area());
}
}
|
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package main
import (
"fmt"
"math"
)
type Rectangle struct {
width float64
height float64
}
type Circle struct {
radius float64
}
type Areable interface {
area() float64
}
func (r Rectangle) area() float64 {
return r.width * r.height
}
func (c Circle) area() float64 {
return c.radius * c.radius * math.Pi
}
func main(){
ra := Rectangle{5,5}
ca := Circle{2.5}
fmt.Println(ra.area())
fmt.Println(ca.area())
}
|
相关文章教程:golang教程
以上就是golang与java语法上的区别的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
golang 快餐 - 环境变量
详解使用air自动重载代码
windows10下编译go项目为linux可执行文件
golang type什么意思
[系列] - go-gin-api 路由中间件 - jaeger 链路追踪(六)
一篇文章带你入门go语言基础之并发
go无缓冲通道的陷阱
golang可以写web吗?
golang 可以把包名去掉吗?
golang是多线程模式吗?
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » golang与java语法上的区别