看似微不足道的 class 示例将无法编译
Seemingly trivial class example will not compile
我正在尝试配置特定类型的属性,并保证不会对 getter 为 nil。这适用于 String
或 URI
实例变量,但是当尝试对 HTTP::Client
执行相同的操作时,编译器会给出一个错误,即实例变量未在所有初始化方法中初始化。
require "http/client"
class Server
getter uri : URI
getter foo : String
getter connnection : HTTP::Client
def initialize(@uri)
@foo = "Bar"
@connection = HTTP::Client.new @uri
end
end
编译器给出的完整错误是:
Error in src/server.cr:6: expanding macro
getter connnection : HTTP::Client
^
in macro 'getter' expanded macro: macro_4613328608:113, line 4:
1.
2.
3.
> 4. @connnection : HTTP::Client
5.
6. def connnection : HTTP::Client
7. @connnection
8. end
9.
10.
11.
12.
instance variable '@connnection' of Server was not initialized directly in all of the 'initialize' methods, rendering it nilable. Indirect initialization is not supported.
如何正确初始化 @connection
实例变量,以便 crystal 编译器满意?
这对我有用。正如上面所指出的,你有一个错字,所以可能甚至没有必要让它成为 nilable。
require "http/client"
class Server
getter uri : URI
getter foo : String
getter connection : HTTP::Client?
def initialize(@uri)
@foo = "Bar"
@connection = HTTP::Client.new @uri
end
end
Server.new(URI.parse("https://www.google.com"))
你打错了:
require "http/client"
class Server
getter uri : URI
getter foo : String
getter connnection : HTTP::Client
# ^
def initialize(@uri)
@foo = "Bar"
@connection = HTTP::Client.new @uri
end
end
我正在尝试配置特定类型的属性,并保证不会对 getter 为 nil。这适用于 String
或 URI
实例变量,但是当尝试对 HTTP::Client
执行相同的操作时,编译器会给出一个错误,即实例变量未在所有初始化方法中初始化。
require "http/client"
class Server
getter uri : URI
getter foo : String
getter connnection : HTTP::Client
def initialize(@uri)
@foo = "Bar"
@connection = HTTP::Client.new @uri
end
end
编译器给出的完整错误是:
Error in src/server.cr:6: expanding macro
getter connnection : HTTP::Client
^
in macro 'getter' expanded macro: macro_4613328608:113, line 4:
1.
2.
3.
> 4. @connnection : HTTP::Client
5.
6. def connnection : HTTP::Client
7. @connnection
8. end
9.
10.
11.
12.
instance variable '@connnection' of Server was not initialized directly in all of the 'initialize' methods, rendering it nilable. Indirect initialization is not supported.
如何正确初始化 @connection
实例变量,以便 crystal 编译器满意?
这对我有用。正如上面所指出的,你有一个错字,所以可能甚至没有必要让它成为 nilable。
require "http/client"
class Server
getter uri : URI
getter foo : String
getter connection : HTTP::Client?
def initialize(@uri)
@foo = "Bar"
@connection = HTTP::Client.new @uri
end
end
Server.new(URI.parse("https://www.google.com"))
你打错了:
require "http/client"
class Server
getter uri : URI
getter foo : String
getter connnection : HTTP::Client
# ^
def initialize(@uri)
@foo = "Bar"
@connection = HTTP::Client.new @uri
end
end