计算不同维度的向量的模
julia> abstract type Pointy{T} end
julia> mutable struct Point1D{T}<:Pointy{T}
x::T
end
julia> mutable struct Point2D{T}<:Pointy{T}
x::T
y::T
end
julia> mutable struct Point3D{T}<:Pointy{T}
x::T
y::T
z::T
end
julia> function module_t(p::Pointy)
m=0
for field in fieldnames(p)
m+=getfield(p,field)^2
end
sqrt(m)
end
module_t (generic function with 1 method)
julia> module_t(Point1D{Int64}(1))
ERROR: MethodError: no method matching fieldnames(::Point1D{Int64})
Closest candidates are:
fieldnames(::Core.TypeofBottom) at reflection.jl:179
fieldnames(::Type{var"#s9"} where var"#s9"<:Tuple) at reflection.jl:181
fieldnames(::DataType) at reflection.jl:176
…
Stacktrace:
[1] module_t(p::Point1D{Int64})
@ Main .\REPL[5]:3
[2] top-level scope
@ REPL[6]:1
如何写是对的