问题描述
我正在R中工作,我想定义一些我(或我的合作者之一)无法更改的变量。在C ++中,我可以这样做:
I'm working in R, and I'd like to define some variables that I (or one of my collaborators) cannot change. In C++ I'd do this:
const std::string path( "/projects/current" );
如何用R编程语言做到这一点?
How do I do this in the R programming language?
为清楚起见进行编辑:我知道我可以在R中定义这样的字符串:
Edit for clarity: I know that I can define strings like this in R:
path = "/projects/current"
我真正想要的是一种语言结构,可以保证没有人可以更改相关的值
What I really want is a language construct that guarantees that nobody can ever change the value associated with the variable named "path."
编辑以响应评论:
从技术上讲,const是一个编译时保证,但是在我看来R解释器将抛出一条错误消息来停止执行,这在我看来是有效的。例如,看看当您尝试将值分配给数字常量时发生了什么。
It's technically true that const is a compile-time guarantee, but it would be valid in my mind that the R interpreter would throw stop execution with an error message. For example, look what happens when you try to assign values to a numeric constant:
> 7 = 3
Error in 7 = 3 : invalid (do_set) left-hand side to assignment
所以我真正想要的是一种语言功能,该功能允许您一次只分配一次值,并且在尝试为声明为const的变量分配新值时应该出现某种错误。我不在乎该错误是否在运行时发生,尤其是在没有编译阶段的情况下。从维基百科的定义上看,从技术上讲,这可能不是const,但是非常接近。在R编程语言中,这似乎也不可能。
So what I really want is a language feature that allows you to assign values once and only once, and there should be some kind of error when you try to assign a new value to a variabled declared as const. I don't care if the error occurs at run-time, especially if there's no compilation phase. This might not technically be const by the Wikipedia definition, but it's very close. It also looks like this is not possible in the R programming language.
推荐答案
请参见 lockBinding
:
a <- 1
lockBinding("a", globalenv())
a <- 2
Error: cannot change value of locked binding for 'a'
这篇关于在R中声明Const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!