- 1
- 2
- 3
- 4
string buf;
...
char c_buf[MAX_LEN];
strncpy(c_buf, buf.c_str(), MAX_LEN);
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+144
string buf;
...
char c_buf[MAX_LEN];
strncpy(c_buf, buf.c_str(), MAX_LEN);
в чём ошибка?
+1
Конструктор по умолчанию?
Не, не слышали.
Рефлексией итерируемся по свойствам и вызываем функцию инициализации полей ))))))))))))))
0
type NetworkLoadingState = {
state: "loading";
};
type NetworkFailedState = {
state: "failed";
code: number;
};
type NetworkSuccessState = {
state: "success";
response: {
title: string;
duration: number;
summary: string;
};
};
type NetworkState =
| NetworkLoadingState
| NetworkFailedState
| NetworkSuccessState;
function logger(state: NetworkState): string {
switch (state.state) {
case "loading":
return "Downloading...";
case "failed":
// The type must be NetworkFailedState here,
// so accessing the `code` field is safe
return `Error ${state.code} downloading`;
case "success":
return `Downloaded ${state.response.title} - ${state.response.summary}`;
default:
return "<error>";
}
}
function main() {
print(logger({ state: "loading" }));
print(logger({ state: "failed", code: 1.0 }));
print(logger({ state: "success", response: { title: "title", duration: 10.0, summary: "summary" } }));
print(logger({ state: "???" }));
print("done.");
}
Ура... радуйтесь.... я вам еще говнокодца поднадкинул... ну и перекопал же говна в коде что бы это сделать. Дампик тут.. https://pastebin.com/u7XZ00LV Прикольно получается если скомпилить с оптимизацией то нихрена от кода не остается. и результат работы
C:\temp\MLIR_to_exe>1.exe
Downloading...
Error 1 downloading
Downloaded title - summary
<error>
done.
+5
inkanus-gray
gost
syoma
Вернитесь.
+2
Function/method calling convention. Here’s a simple example:
struct Foo { a: i32 }
impl Foo { fn bar(&mut self, val: i32) { self.a = val + 42; } }
fn main() {
let mut foo = Foo { a: 0 };
foo.bar(foo.a);
}
For now this won’t compile because of the borrowing but shouldn’t the compiler be smart enough to create a copy of foo.a before call?
I’m not sure but IIRC current implementation first mutably borrows object for the call and only then tries to borrow the arguments.
Is it really so and if yes, why?
Update: I’m told that newer versions of the compiler handle it just fine but the question still stands (was it just a compiler problem or the call definition has been changed?).
The other thing is the old C caveat of function arguments evaluation. Here’s a simple example:
let mut iter = “abc”.chars();
foo(iter.next().unwrap(), iter.next().unwrap(), iter.next().unwrap());
So would it be foo('a','b','c') or foo('c','b','a') call. In C it’s undefined because it depends on how arguments are passed on the current platform
(consider yourself lucky if you don’t remember __pascal or __stdcall).
In Rust it’s undefined because there’s no formal specification to tell you even that much.
And it would be even worse if you consider that you may use the same source for indexing the caller object like
handler[iter.next().unwrap() as usize].process(iter.next().unwrap()); in some theoretical bytecode handler
(of course it’s a horrible way to write code and you should use named temporary variables but it should illustrate the problem).
https://codecs.multimedia.cx/2020/09/why-rust-is-not-a-mature-programming-language/
0
Срочно нужна помощь с засылкой на хабр!
Желательно перед этим почитать от того, что не пропустит анальная модерация и сектанты.
Предложения так же жду в комментах. По тексту и в целом.
https://tsar1997.blogspot.com/2020/05/blog-post_54.html
Исходник пасты - просьба кидать патчи. Позже зашлю на хабр.
https://pastebin.com/raw/haeHPx89
−6
// определяем приоритет операций
private int getPriority(char currentCharacter){
if (Character.isLetter(currentCharacter)) return 4;
else if (currentCharacter =='*'|| currentCharacter=='/') return 3;
else if (currentCharacter == '+'|| currentCharacter=='-') return 2;
else if (currentCharacter == '(') return 1;
else if (currentCharacter ==')') return -1;
else return 0;
}
Калькулятор стажера
0
def __repr__(self):
return 'environ({{{}}})'.format(', '.join(
('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value))
for key, value in self._data.items())))
{{впечатляйте{с{GNU/Python}}}}
0
С днём Прогромиста!
Ко-кок
http://torvaldsfinger.com/
−1
Когда наконец заработает гвфорум?