Comparison#

Generics#

FeatureGoC++
ParadigmParametric PolymorphismMetaprogramming
ConstraintInterface-based (Type Sets)Concepts (C++20), SFINAE
SpecializationNot SupportedSupported
MetaprogrammingNot SupportedTuring-complete

Go generics focus on simplicity and clarity. They use type parameters constrained by interfaces.

Generic Function#

eg.

// T is constrained by 'any'
func Print[T any](s []T) {
    for _, v := range s {
        fmt.Print(v, " ")
    }
}

// T is constrained by 'comparable' (supports == and !=)
func Find[T comparable](s []T, val T) int {
    for i, v := range s {
        if v == val {
            return i
        }
    }
    return -1
}

Data Structure#

Syntax: type STRUCT_NAME[<type parameter> <type constraint>] struct {}

eg.

type Stack[T any] struct {
    vals []T
}

func (s *Stack[T]) Push(val T) {
    s.vals = append(s.vals, val)
}

Type Constraints#

  • any: Alias for interface{}. Allows any type.
  • comparable: Predefined interface for types that support == and !=.
  • Custom Interface: Any interface can be used as a constraint.
  • ~ Operator: Used in interface definitions to match types with the same underlying type.

eg.

type Integer interface {
    ~int | ~int8 | ~int16 | ~int32 | ~int64
}

func Add[T Integer](a, b T) T {
    return a + b
}

C++ templates are highly flexible and support complex metaprogramming, allowing for compile-time logic and optimization.

Function Template#

eg.

template <typename T>
void Print(const std::vector<T>& v) {
    for (const auto& i : v) {
        std::cout << i << " ";
    }
}

Class Template#

eg.

template <typename T>
class Stack {
private:
    std::vector<T> vals;
public:
    void Push(T val) {
        vals.push_back(val);
    }
};

Slicing#

Python list slicing creates a shallow copy. Modifying the new list does not affect the original list.

eg.

a = [1, 2, 3]
b = a[:]
b[0] = 9
print(a) # [1, 2, 3]

Go slice slicing shares the same underlying array. Modifying the new slice affects the original slice.

eg.

a := []int{1, 2, 3}
b := a[:]
b[0] = 9
fmt.Println(a) // [9 2 3]

Switch#

  • Fall-through: Cases fall through by default. A break statement is required to prevent falling through to the next case.
  • Supported Types: Only integer types such as char, int, and long long are supported.

eg.

const char *words[] = {"a", "cow", "smile", "gopher", "octopus", "anthropologist"};
int num_words = sizeof(words) / sizeof(words[0]);

for (int i = 0; i < num_words; i++) {
  size_t size = strlen(words[i]);

  switch (size) {
    case 1:
    case 2:
    case 3:
    case 4:
      printf("%s is a short word!\n", words[i]);
      break;
    case 5:
      printf("%s is exactly the right length: %zu\n", words[i], size);
      break;
    case 6:
    case 7:
    case 8:
    case 9:
      break;
    default:
      printf("%s is a long word!\n", words[i]);
  }
}
  • Fall-through: Cases do not fall through by default. An explicit fallthrough keyword is required to force fall-through behavior.
  • Supported Types: Any type that can be compared with == is supported. This includes all built-in types except slices, maps, channels, functions, and structs that contain fields of these types.
  • Multiple Values: Multiple values can be matched in a single case using a comma-separated list.
  • Blank Switch: A switch without an expression is equivalent to switch true. Useful for clean if-else-if chains.

eg.

words := []string{"a", "cow", "smile", "gopher", "octopus", "anthropologist"}
for _, word := range words {
    switch size := len(word); size {
    case 1, 2, 3, 4:
        fmt.Println(word, "is a short word!")
    case 5:
        wordLen := len(word)
        fmt.Println(word, "is exactly the right length:", wordLen)
    case 6, 7, 8, 9:
    default:
        fmt.Println(word, "is a long word!")
    }
}

Variadic / Unpacking#

FeatureCC++Go (...)Python (*)
Declaration: Packingvoid f(int n, ...) — <stdarg.h>
  • Heterogeneous: Args&&... args — Variadic Template
  • Homogeneous: initializer_list<T>
  • C-compat: ...
func f(args ...T)def f(*args, **kwargs):
Call Site: UnpackingNot Supported — requires va_list wrapperf(args...), f(PATTERN...) — Pack Expansionf(slice...)f(*seq, **dict)
Evaluation / MechanismRuntime stack traversal via va_list, single function
  • Args...: Compile-time instantiation per argument combination, zero runtime overhead
  • initializer_list<T>: lightweight const array view
Allocates runtime Slice []T, single functionAllocates runtime tuple / dict, single function
Type Safety❌ No type or count check, runtime UB on mismatch✅ Args... enforces 100% compile-time type safety across heterogeneous types with Perfect ForwardingSingle type T only, heterogeneous types require ...any boxingDynamic typing, resolved at runtime
Unpacking CapabilityNot SupportedFull pattern replication: wrap(args)... → wrap(a1), wrap(a2) and C++17 Fold Expressions (args + ...)Unpacks slice elements as-is onlyUnpacks iterable/mapping elements as-is only

C handles variadic functions using macros defined in the <stdarg.h> header.

Declaration: Packing#

  • Requires at least one named fixed parameter, followed by ... as the final parameter.
  • Iterates over arguments using va_list, va_start, va_arg, and va_end.
  • The compiler performs no type or argument count checking; callers must communicate the count explicitly or via format strings.

eg.

#include <stdio.h>
#include <stdarg.h>

void print_ints(int count, ...) {
    va_list args;
    va_start(args, count);
    for (int i = 0; i < count; i++) {
        int val = va_arg(args, int);
        printf("%d ", val);
    }
    va_end(args);
    printf("\n");
}

int main() {
    print_ints(3, 10, 20, 30);
    return 0;
}

Call Site: Unpacking#

C does not support syntax-level argument unpacking. Arrays cannot be unpacked into variadic calls directly; a separate function accepting a va_list such as vprintf must be provided.

C++ provides distinct mechanisms for handling varying numbers of arguments depending on type homogeneity and compile-time vs. runtime semantics.

Variadic Templates (Args..., C++11)#

Accepts zero or more heterogeneous arguments and instantiates specialized functions at compile time with no runtime container overhead (see Templates: Variadic Templates for details).

  • Declaration: Packing (typename... Args, Args&&... args): Placing ... before the name packs types or function arguments together.
  • Call Site: Unpacking (PATTERN...): Placing ... after an expression replicates the entire pattern to the left for each element, separated by commas.

eg.

#include <iostream>
#include <utility>

template <typename... Args>
auto MySum(Args... args) {
    return (args + ...); // C++17 Fold Expression: expands to (arg1 + (arg2 + arg3))
}

template <typename T, typename... Args>
T Create(Args&&... args) {
    // Replicates the full pattern: std::forward<T1>(arg1), std::forward<T2>(arg2), ...
    return T(std::forward<Args>(args)...);
}

int main() {
    std::cout << MySum(1, 2.5, 3) << '\n'; // 6.5 (heterogeneous: int, double, int)
    return 0;
}

std::initializer_list<T> (C++11)#

Used when all variable arguments share the same type.

  • Unlike vector, elements in an initializer_list are always const.
  • Provides .begin() and .end() member functions, allowing traversal via range for loops.

eg.

#include <iostream>
#include <initializer_list>
#include <string>

void PrintMessages(std::initializer_list<std::string> il) {
    for (const auto &elem : il) { // range for supported via .begin() and .end()
        std::cout << elem << " ";
    }
    std::cout << '\n';
}

int main() {
    PrintMessages({"hello", "world", "c++"}); // Pass arguments in braced list
    return 0;
}

Ellipsis Parameter (...)#

C-compatible variadic syntax (printf, etc.). Offers no type safety and should be avoided in modern C++.

Declaration: Packing#

eg.

func mySum(nums ...int) int {
  total := 0
  for _, n := range nums {
    total += n
  }
  return total
}

func main() {
  fmt.Println(mySum(1, 2, 3))
}

Call Site: Unpacking#

eg.

func main() {
  s := []int{1, 2, 3}
  s = append(s, s...)
  fmt.Println(s) // [1, 2, 3, 1, 2, 3]
}

Declaration: Packing#

eg.

def mySum(*args):
  return sum(args)

if __name__ == "__main__":
  print(mySum(1, 2, 3))

Call Site: Unpacking#

eg.

def mySum(*args):
  return sum(args)

if __name__ == "__main__":
  print(mySum(1, 2, 3))
  print(mySum(*[1, 2, 3]))

Exception Handling#

FeaturePythonC++
Syntaxtry - except - else - finallytry - catch (No finally; relies on RAII)
Throwable TypesMust derive from BaseExceptionAny type (primitives like int, strings, class objects)
Catch-allexcept: or except Exception:catch (...) (Ellipsis)
Uncaught ExceptionPrints traceback and exits interpreterPropagates up call stack; calls std::terminate() $\rightarrow$ abort()
Resource Cleanupfinally block, with statement (Context Manager)RAII (local destructors automatically invoked during stack unwinding)
Idiom / PhilosophyEAFP (actively used for standard control flow)Zero-cost model (reserved exclusively for truly exceptional errors)

Python exception handling is built around the EAFP (“Easier to ask for forgiveness than permission”) idiom. Exceptions are widely used not only for error handling but also for ordinary control flow (such as StopIteration signaling the completion of an iterator).

  • else block: Executes only if no exception was raised in the try block.
  • finally block: Always executes regardless of whether an exception occurred or was handled; commonly used for cleanup.
  • with statement (Context Manager): Safely releases resources via __enter__ and __exit__ even if exceptions occur.
  • All exception objects must derive from BaseException (typically subclassing Exception).

eg.

def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError as e:
        print("Cannot divide by zero:", e)
    except Exception as e:
        print("Unexpected error:", e)
    else:
        print("Calculation successful:", result)
    finally:
        print("Cleanup block always executed")

divide(10, 2)
divide(10, 0)

C++ exception handling is designed strictly for truly exceptional error conditions. While it imposes no runtime overhead on successful execution (Zero-cost exception model), throwing an exception incurs significant runtime cost due to stack unwinding.

  • Handler Search and Propagation (Stack Unwinding): If the current try block’s catch clauses do not provide a matching type, the exception propagates up to the caller function, unwinding the stack and calling destructors for all local objects along the way.
  • Uncaught Exception: If no matching handler is found anywhere in the call chain up to main(), the runtime invokes std::terminate(), which by default calls abort() to immediately terminate the program.
  • RAII Instead of finally: C++ lacks a finally block. Instead, it relies on RAII (Resource Acquisition Is Initialization): destructors of stack-allocated objects are automatically executed during stack unwinding to release resources.
  • Arbitrary Throwable Types: Any type can be thrown—including primitives like int, string literals, or custom class objects. Standard practice strongly recommends throwing types derived from std::exception and catching by reference: catch (const std::exception &e) to prevent object slicing.
  • catch (...): The universal catch-all handler (ellipsis) that matches any exception type.

eg.

#include <iostream>
#include <stdexcept>

void Process(int val) {
    if (val < 0) {
        throw std::invalid_argument("Negative values not allowed");
    }
    if (val == 0) {
        throw 0; // Primitive types can also be thrown
    }
}

int main() {
    try {
        Process(-1);
    } catch (const std::invalid_argument &e) {
        std::cerr << "Invalid argument: " << e.what() << '\n';
    } catch (int errCode) {
        std::cerr << "Caught error code: " << errCode << '\n';
    } catch (...) {
        // Universal catch-all handler
        std::cerr << "Caught unknown exception\n";
    }
    return 0;
}