Crystal的命名参数快捷方式

问题描述 投票:1回答:1

在下面的代码中,必须重复命名参数,是否可以缩短表达式?

struct Figure
  getter id :      String
  getter hash :    String
  getter title :   String

  def initialize(@id, @hash, @title)
  end
end

id = "Figure 1", hash = "123", title = "Some figure"

Figure.new id: id, hash: hash, title: title

类似于下面的代码,但仍将其命名为位置错误?

Figure.new id, hash, title

或者也许

Figure.new{ id, hash, title }
crystal-lang
1个回答
1
投票

我不知道一种缩短方法。

我认为当将局部变量的名称与方法参数的名称绑定在一起时,这将是一种危险的语义,因为在一个地方更改事物会在另一个地方产生不可预见的影响。

对于大多数用例,使用位置参数应该没问题。而且,如果要跳过某些参数,可以只组合位置参数和命名参数。

© www.soinside.com 2019 - 2024. All rights reserved.