java与golang语法比较(一)
本文内容纲要:
-变量声明与赋值
-异常处理
-参数传递
-多态
变量声明与赋值
-
Java
inti;//声明 intj=1;//声明+赋值
-
Go
variint//声明 i:=1//声明+赋值
- 变量声明:var是关键字,格式:var变量名称变量类型
- 变量声明与赋值::=符号支持自动推导类型
异常处理
-
Java
//声明 intexecute(){ thrownewRuntimeException(”msg”);//有错误 return0;//无错误 } //处理 try{ intcode=execute(); }catch(Exceptione){ //TODO异常情况如何处理 }
-
Go
//声明 funcExecute()(int,error){ return1,error.New(“msg”)//有错误 return0//无错误 } //处理 ifcode,err=c.Execute();err!=nil{ //TODO异常情况如何处理 }
- go的异常是做为函数返回值的,通过判断是否存在error,来判断异常。(不能够像Java一样抛出异常)
- go的if语句支持初始条件,即先执行if之后的语句(分号之前),再执行分号之后的判断语句,此语句经常用于异常处理。
- go的大括号必须在行末
- go函数或者变量为”公有”,首字母大写,”私有”则小写。
参数传递
-
Java
略,见Go实现中的注释
-
Go
packagemain//入口必须是main import"fmt"//引包
typePeoplestruct{//结构体,类似Java中的class ageint//变量声明,变量类型放在后面 namestring } //类似Java方法的函数 funcchange(pPeople){//func为关键字 p.age=18 } //传递指针 funcchange2(p*People){ p.age=18 } funcmain(){ p:=People{22,"lsq"}//新建对象并赋值 change(p)//调用函数change,传递对象 fmt.Println(p)//控制台打印 change2(&p)//调用函数change2,传递指针 fmt.Println(p) } //执行结果 {22'lsq'} {18'lsq'}
- change函数是传递的对象,函数调用的时候,会拿到对象的拷贝。
- change2函数是传递的指针,函数调用的时候,会拿到一个指向改对象的指针。
- go没有引用传递
多态
此例有点长,是一个求面积的问题,针对与圆形和矩形两种类型
-
Java
importjava.lang.Math; publicclassPolymorphism{ publicstaticclassRectangleimplementsAreable{//矩形 doublewidth; doubleheight; publicRectangle(doublewidth,doubleheight){
this.width=width; this.height=height;} publicdoublearea(){ returnwidth*height;} } publicstaticclassCircleimplementsAreable{//圆形 doubleradius; publicCircle(doubleradius){ this.radius=radius;} publicdoublearea(){ returnradius*radius*Math.PI;} }publicstaticinterfaceAreable{
doublearea(); } publicstaticvoidmain(String[]args){ Areablearear=newRectangle(5.0,5.0); Areableareac=newCircle(2.5); System.out.println(arear.area()); System.out.println(areac.area()); } }
-
Go
packagemain import( "fmt" "math" )
typeRectanglestruct{//矩形 widthfloat64 heightfloat64 } typeCirclestruct{//圆形 radiusfloat64 }
typeAreableinterface{//接口:一组method签名的组合,通过interface来定义对象的一组行为。 //只要是实现了interface中的所有的method的结构体,就可以认为是这个interface的实例,Ducktyping area()float64 } func(rRectangle)/*函数的接受者Receiver/area()float64/返回值类型*/{
returnr.width*r.height }func(cCircle)/*函数的另一个接受者Receiver/area()float64/返回值类型*/{
returnc.radius*c.radius*math.Pi }funcmain(){ ra:=Rectangle{5,5} ca:=Circle{2.5} fmt.Println(ra.area()) fmt.Println(ca.area()) }
本文内容总结:变量声明与赋值,异常处理,参数传递,多态,
原文链接:https://www.cnblogs.com/langshiquan/p/9937866.html