ITeye博客

Julia之类型的蹩脚之处

myten · 2018-08-28 13:11 · Julia Language · 编程语言 · Markdown

面向对象,耳熟能详。Julia也算是面向对象的,那么今天说说痛点----类型。

像java允许有父类,抽象类,并且类里边可以定义方法,写起代码来不亦乐乎。

目前的Julia只允许方法属于模块,而不能归属于类。这个实在不爽。但今天说的事情可能会让更多人不爽。

官方文档上的前三个,Abstract Types, Primitive Types,Composite Types

先说抽象类型吧。

我试着自己定义个抽象类型,如官网所讲

abstract type «name» end
abstract type «name» <: «supertype» end

 假设我需要抽象出一个场景,Student<:Person,学生人群隶属于人类

abstract type Person
end

 

abstract type Student<:Person
end

 嘿,挺好,到此为止简直是完美。不过,我想,学生这一层就不要在抽象了吧。干脆去掉abstract关键字。

于是乎,意外就出现了。编译执行根本不能通过。我只想fuck 下边的红字提示的作者。

ERROR: LoadError: syntax: extra token "Student" after end of expression

那好吧,退一步,既然是抽象类,总应该有姓名和年龄这两个字段吧。

于是乎我改进一下。

abstract type Person
name
age:Int64
end

 加两个字段吧。然后就又出意外了,无语了。

ERROR: LoadError: syntax: "abstract type" expected "end", got "name"

反了天了啊,不能添加字段在类型里。也就是说type不等同于java 的 class。好吧,这就是抽象类型。

 

原始类型

官网给出的解释和示范

A primitive type is a concrete type whose data consists of plain old bits. Classic examples of primitive types are integers and floating-point values. Unlike most languages, Julia lets you declare your own primitive types

 

primitive type «name» «bits» end
primitive type «name» <: «supertype» «bits» end

 

看明白了,允许你自己定义原始类型,很高大上啊,就好比java能让你自己定义和int平起平坐的类型了。但是,有个毛用啊?我要面向对象,不要这些没用的。

 

最后来看看 官网说的复合类型

Composite types are called records, structs, or objects in various languages. A composite type is a collection of named fields, an instance of which can be treated as a single value. In many languages, composite types are the only kind of user-definable type, and they are by far the most commonly used user-defined type in Julia as well.

一大堆废话,然后又说自己很牛逼啊。

给了个示范例子

struct Foo
           bar
           baz::Int
           qux::Float64
       end

 我靠,type消失了,变成struct了,之前就说过,这里边不能定义方法只能定义字段。

来来来,试试

struct Student
name
age::Int8
end
s=Student("jack",12)
println(s.age)
s.age=22

 定义个结构体,创建个对象,输出年龄,改变年龄,一切都很流畅啊。但是,抱歉。s.age=22到这里就会报错。

ERROR: LoadError: type Student is immutable

告诉你了,非可变类型。所以,没有 mutable 修饰 struct ,那么就是 final类型咯。。

 

好,接着说,Student怎么才能具备一个打招呼的功能呢?看来我们需要定义个方法给他

mutable struct Student
name
age::Int8
sayHi::Function
end

 这样就OK了,但是具备了这些还是一个抽象的结构体并不是对象。我们需要使用它。

mutable struct Student
name
age::Int8
sayHi::Function
end

function jackSayHi()
  println("GOOD")
end
s=Student("jack",12,jackSayHi)
s.sayHi()
function tomSayHi()
  println("Well")
end
b=Student("tom",22,tomSayHi)
b.sayHi()

 完整代码就变成了这样。这一点方法的定义和使用 和C 类似。反正都是在结构体里允许定义,不允许实现。但就是用起来不是那么爽啊。设计者就是要设计成这样,喜欢的人可能会捧到天上。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。