This question already has answers here:
How to create a formatted String out of a literal in Rust?
(2 answers)
Closed 4 months ago.
Is there a way to use String::from with variables? I tried using it similarly to println!(), but doesn't seem to work.
String::from("[INFO]: {}", message)
Expected:
// Returns: "[INFO]: My info message here"
Got:
// Error: argument unexpected
Rust doesn’t really practice variadic functions because we have big metaprogramming potential: modern generic system and about 6 types of macros.
In this case you need the format macro:
format!("[INFO]: {}", message)
This question already has answers here:
What do ellipsis [...] mean in a list?
(5 answers)
Closed 2 years ago.
I've run into this unseen list object, when I tried to play with list append, and I've searched hard but unable to find much information. So this is what's happening:
L = ['dinosaur']
L.append(('theropoda', L))
print(L)
# ['dinosaur', ('theropoda', [...])]
Questions - what's the [...] means here? Thanks.
As mentioned in the comments, Python will not attempt to include a circular/recursive reference in the representation of a list.
It would appear that the __repr__ function (also used by lists to create the string for printing) is implemented via reprlib with recursive support. Without it, you would end up with a RecursionError as to output the list, Python must include the nested version of the list, which also needs the nested version, and so on. Instead, it outputs the special value of ... which indicates to you that it is a recursive reference.
Is it possible to take any Rust code and make it work in only one line (without any line breaks)? In particular, it should work exactly like the "normal" multi line code:
if it's an executable, the runtime behavior should be the same.
if it's a library, the documentation and .rlib file should be the same.
This is a purely theoretical question and I don't plan on actually writing my Rust code like this :P
I know that most typical Rust code can be written in one line. Hello world is easy-peasy:
fn main() { println!("Hello, world"); }
Are there any Rust constructs that can't be written in one line? I thought of a few candidates already:
Doc comments. I usually see them written as /// or //! and they include everything until the end of the line.
Macros, especially procedural ones, can do some strange unexpected things. Maybe it is possible to construct macros that only work on multiple lines?
String literals can be written over multiple lines in which case they will include the linebreaks. I know that those line breaks can also be written as \n, but maybe there is something about multi-line strings that does not work in a single line? Maybe something something about raw string literals?
Maybe some planned future extensions of Rust?
Probably many other things I didn't think of...
Out of curiosity, I did a quick read through of Rust's Lexer Code and there is only one case (that I noticed) which requires a newline and can not be rewritten any other way. As people have pointed out, there are directly equivalent ways to write doc comments, string literals, and macros which can be done on a single line.
That being said, this is technically not considered Rust syntax. However, it has been part of rustc since the creation of rustc_lexer (4 years ago) and likely long before that so I'm going to count it. Plus if we squint really hard then it kind of looks like it might just fit the restriction of "if it's an executable, the runtime behavior should be the same".
Rust files allow the inclusion of a shebang on the first line. Since shebang's are a Unix convention, Rust needs to follow the existing standard (which requires a line break before the rest of the file contents). For example, it is not possible to write this Rust file without any newline characters in a way that preserves the behavior when run (cough on systems that support shebangs cough):
#!/usr/bin/rustrun
fn main() {
println!("Hello World!");
}
Rust Playground (You won't be able to try using the shebang on Rust Playground, but at least you can see it compiles and can not be reduced to a single line)
For anyone who is curious, here is how it is described in the lexer code:
/// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun",
/// but shebang isn't a part of rust syntax.
pub fn strip_shebang(input: &str) -> Option<usize> {
// Shebang must start with `#!` literally, without any preceding whitespace.
// For simplicity we consider any line starting with `#!` a shebang,
// regardless of restrictions put on shebangs by specific platforms.
if let Some(input_tail) = input.strip_prefix("#!") {
// Ok, this is a shebang but if the next non-whitespace token is `[`,
// then it may be valid Rust code, so consider it Rust code.
let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| {
!matches!(
tok,
TokenKind::Whitespace
| TokenKind::LineComment { doc_style: None }
| TokenKind::BlockComment { doc_style: None, .. }
)
});
if next_non_whitespace_token != Some(TokenKind::OpenBracket) {
// No other choice than to consider this a shebang.
return Some(2 + input_tail.lines().next().unwrap_or_default().len());
}
}
None
}
https://github.com/rust-lang/rust/blob/e1c91213ff80af5b87a197b784b40bcbc8cf3add/compiler/rustc_lexer/src/lib.rs#L221-L244
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Annoying PHP error: “Strict Standards: Only variables should be passed by reference in”
I have this line of code,
$extension=end(explode(".", $srcName));
when I fun my function I get
PHP Strict Standards: Only variables should be passed by reference in
I am not sure how to solve this
The function end() requires a variable to be passed-by-reference and passing the return-value of a function doesn't acheive this. You'll need to use two lines to accomplish this:
$exploded = explode(".", $srcName);
$extension = end($exploded);
If you're simply trying to get a file-extension, you could also use substr() and strrpos() to do it in one line:
$extension = substr($srcName, strrpos($srcName, '.'));
Or, if you know the number of .'s that appear in the string, say it's only 1, you can use list() (but this won't work if there is a dynamic number of .'s:
list(,$extension) = explode('.', $srcName);
This question already has answers here:
mysqli bind_param() expected to be a reference, value given
(3 answers)
Closed 12 months ago.
Ok, this is a weird problem, so please bear with me as I explain.
We upgraded our dev servers from PHP 5.2.5 to 5.3.1.
Loading up our code after the switch, we start getting errors like:
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in /home/spot/trunk/system/core/Database.class.php on line 105
the line mentioned (105) is as follows:
call_user_func_array(Array($stmt, 'bind_param'), $passArray);
we changed the line to the following:
call_user_func_array(Array($stmt, 'bind_param'), &$passArray);
at this point (because allow_call_time_pass_reference) is turned off, php throws this:
Deprecated: Call-time pass-by-reference has been deprecated in /home/spot/trunk/system/core/Database.class.php on line 105
After trying to fix this for some time, I broke down and set allow_call_time_pass_reference to on.
That got rid of the Deprecated warning, but now the Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference warning is throwing every time, with or without the referencing.
I have zero clue how to fix this. If the target method was my own, I would just reference the incoming vars in the func declaration, but it's a (relatively) native method (mysqli).
Has anyone experienced this? How can I get around it?
Thank you.
I just experienced this same problem, calling bind_param via call_user_func_array and passing an array of parameters. The solution is to modify the values in the array to be referenced. It's not elegant but it works.
call_user_func_array(array($stmt, 'bind_param'), makeValuesReferenced($passArray));
function makeValuesReferenced($arr){
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
You are passing an array of elements ($passArray). The second item inside the passed array needs to be a reference, since that is really the list of items you are passing to the function.
Actually, be aware that there is a bug with PHP 5.3.1 concerning references and all call family of functions:
PHP Bugs #50394: Reference argument converted to value in __call
The behavior you are seeing might be a result of this bug and any attempt to fix it code wise may cause problems in the long run.
The problem has been fixed in the SVN version of PHP. Until 5.3.2 is released, you may compile a new version for use, or downgrade to an earlier version.
We were experiencing this same problem with this code:
call_user_func(array($strCartHandler, 'CartPurchaseEvent'), $strCartEvent, $objToUser, null, $this);
My solution was to just skip call_user_func altogether and do this:
$strCartHandler::CartPurchaseEvent($strCartEvent, $objToUser, null, $this);
I think what is deprecated is passing a reference through a function. In the function definition you do something like:
function(&$arg) {
}
This doesn't help you much but you probably need not pass the reference anyway. I guess you could try a wrapper function.
function wrapper($stmt, &$passArray) {
call_user_func_array($stmt, $passArray);
}
I think the mysqli_bind_param() and mysqli_bind_result() functions are very awkward to use. I've encountered the same difficulty as you describe using them in combination with call_user_func_array()
My workaround was to stop using mysqli and instead use PDO_mysql. It has a much easier usage:
$pdoStmt->execute( $passArray );
This will helps:
<?php
call_user_func_array(Array($stmt, 'bind_param'), array(&$passArray));
function bind_param ($val)
{
$val = (is_array($val)) ? $val[0] : $val;
// operations...
}
?>
The second paramer Must be an array. apparently this was only enforced in 5.3
I've got a similar problem, the current code didnt work:
$query="Select id,name FROM mytable LIMIT ?,?";
$params=Array('ii');
array_push($params,$from_var);
array_push($params,$to_var);
...
$stmt=$link->prepare("$query");
$ref=new ReflectionClass('mysqli_stmt');
$method=$ref->getMethod("bind_param");
$method->invokeArgs($stmt,$params);
...
It told that "Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given"
And then, in despair, I've tried to take $from_var and $to_var in quotes. And it worked!
$params=Array('ii');
array_push($params,"$from_var");
array_push($params,"$to_var");
Hope, it will help somebody, good luck :)