Nim编译报错:Option类型表达式需丢弃,模板调用问题咨询
discard still cause a compilation error? The Issue Breakdown
Let's start by reproducing your original problem and the fix you landed on.
Original (Failing) Code
import options template p[T] = none(T) discard p[int]
Error: templat.nim(5, 10) Error: expression 'none(int)' is of type 'Option[system.int]' and has to be discarded
Fixed (Working) Code
import options template p[T](): untyped = T.none discard p[int]()
Root Cause
The confusion comes down to how Nim treats template definitions by default, and the difference between statement vs. expression templates:
Default Statement Templates
Your original templatetemplate p[T] = none(T)is a statement template—Nim assumes templates without an explicit return type generate executable statements, not values. When you wrotediscard p[int], you tried to pass a statement todiscard, which expects an expression. The template expands to runnone(int)as a standalone statement, which produces anOption[int]value that never gets discarded within the template's context—hence the error.Explicit Expression Templates
By defining the template astemplate p[T](): untyped = T.none, you explicitly mark it as an expression template that returns untyped AST. Nowp[int]()evaluates to the expressionT.none(functionally identical tonone(int)), whichdiscardcan properly handle. Thediscardnow directly manages theOption[int]value generated by the expression, resolving the compiler's complaint.
Quick Side Note
T.none is just syntactic sugar for none(T)—they create the exact same Option[T] value. The fix doesn't rely on this swap; it's the explicit return type definition and the added () in the call that make the difference. The original error message is indeed unhelpful here, as it doesn't clarify the statement vs. expression template distinction.
内容的提问来源于stack exchange,提问作者v.oddou

