有没有办法在julia中为用户创建的类型实现基本算法
例如:
type Foo
bar::Float32
foo::Int32
end
a = Foo(3.23,23)
b = Foo(4.56,54)
c = a+b
Run Code Online (Sandbox Code Playgroud)
我怎么可能这样做?提前致谢
小智 10
您需要显式导入Base函数,以便为它们添加自己的类型的方法.我不确定这是否是最佳方式,但以下内容可让您将两个Foos一起添加.
type Foo
bar::Float32
foo::Int32
end
import Base: +
+(a::T, b::T) where {T<:Foo} = Foo(a.bar+b.bar, a.foo+b.foo)
a = Foo(3.23,23)
b = Foo(4.56,54)
c = a+b
Run Code Online (Sandbox Code Playgroud)