Overload zero for a parametric type

question

#1

Hello, I would like to add a zero function for a custom parametric type.

This code for example

struct Point{T}
	p::T 
end
Point{T}() where T = Point(zero(T))
Point() = Point(0)

can produce “zero” elements with

Point()
Point{Float64}()

But when I try to define

Base.zero(::Point{T}) where T = Point{T}(zero(T))

and call it with zero(Point{Int64})

I get the following error:

ERROR: LoadError: MethodError: no method matching zero(::Type{Point{Int64}})
Closest candidates are:
  zero(::Type{Base.LibGit2.GitHash}) at libgit2/oid.jl:106
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuildItem}) at pkg/resolve/versionweight.jl:82
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuild}) at pkg/resolve/versionweight.jl:124

Why can’t julia dispatch to the right method is this case?


#2

Look at the error message:

Just define a method

Base.zero(::Type{Point{T}}) where T = Point{T}(zero(T))

for the type.


#3

You need ::Type{Point{T}}


#4

Thanks, I see, I thought, just :: in front is enough to tell that it is a type.


#5

No it is unrelated f(::SomeThing) is just a short hand f(unused_argument::SomeThing). So f(::Point) is short for f(unused_point_instance::Point), while f(::Type{Point}) is short for f(WeAlreadyKnowThisIsPoint::Type{Point})