Skip to content

Instantly share code, notes, and snippets.

View perl-static-dynamic-scope.pl
# Perl example of static and dynamic scopes
$x = 10;
sub print_x {
print $x;
}
sub static {
my $x = 20; # doesn't affect
View js-static-scope.js
/**
* JavaScript static scope example.
*/
const x = 10;
function print_x() {
console.log(x);
}
View rust-use-parser.rs
extern crate syntax;
use syntax::Parser;
fn main() {
let mut parser = Parser::new();
let result = parser.parse("2 + 2 * 2");
println!("{:?}", result); // 6
}
View rust-calc-grammar.g
/**
* Calculator grammar to generate parser in Rust.
*/
%lex
%%
// -----------------------------------------------
// Lexical grammar.
View wasm-binary-example.html
<!DOCTYPE html>
<html>
<head>
<title>Wasm</title>
</head>
<body>
<script>
(async () => {
/**
@DmitrySoshnikov
DmitrySoshnikov / rust-dynamic-lazy-static.md
Last active May 21, 2021
Rust notes: dynamic and global static objects
View rust-dynamic-lazy-static.md

Rust notes: dynamic and global static objects

Level: novices, n00bs

Rust is a statically typed language, which helps preventing runtime bugs, and ensures memory safety at compile time, that is with no runtime costs. However, sometimes one may need using dynamic values. Also, Rust doesn't support "out of the box" complex static structures, which still can be solved with some lazy initialization tricks.

Below are some notes on dynamic data types, and global static objects in Rust programming language.

Dynamic objects

View any.rs
use std::fmt::Debug;
use std::any::Any;
// Logger function for any type that implements Debug.
fn log<T: Any + Debug>(value: &T) {
let value_any = value as &Any;
// try to convert our value to a String. If successful, we want to
// output the String's length as well as its value. If not, it's a
// different type: just print it out unadorned.
View map-literal.rs
macro_rules! map(
{ $($key:expr => $value:expr),+ } => {
{
let mut m = ::std::collections::HashMap::new();
$(
m.insert($key, $value);
)+
m
}
};
View field-names.rs
macro_rules! zoom_and_enhance {
(struct $name:ident { $($fname:ident : $ftype:ty),* }) => {
struct $name {
$($fname : $ftype),*
}
impl $name {
fn field_names() -> &'static [&'static str] {
static NAMES: &'static [&'static str] = &[$(stringify!($fname)),*];
NAMES
View stack-params.c
// https://godbolt.org/g/2xOK3B
int foo(int x) {
int y = 20;
return x + y;
}
int main() {
foo(10);
return 0;