Comparison#
Generics#
| Feature | Go | C++ |
|---|---|---|
| Paradigm | Parametric Polymorphism | Metaprogramming |
| Constraint | Interface-based (Type Sets) | Concepts (C++20), SFINAE |
| Specialization | Not Supported | Supported |
| Metaprogramming | Not Supported | Turing-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 forinterface{}. 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
breakstatement is required to prevent falling through to the next case. - Supported Types: Only integer types such as
char,int, andlong longare 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
fallthroughkeyword 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 cleanif-else-ifchains.
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#
| Feature | C | C++ | Go (...) | Python (*) |
|---|---|---|---|---|
| Declaration: Packing | void f(int n, ...) — <stdarg.h> |
| func f(args ...T) | def f(*args, **kwargs): |
| Call Site: Unpacking | Not Supported — requires va_list wrapper | f(args...), f(PATTERN...) — Pack Expansion | f(slice...) | f(*seq, **dict) |
| Evaluation / Mechanism | Runtime stack traversal via va_list, single function |
| Allocates runtime Slice []T, single function | Allocates 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 Forwarding | Single type T only, heterogeneous types require ...any boxing | Dynamic typing, resolved at runtime |
| Unpacking Capability | Not Supported | Full pattern replication: wrap(args)... → wrap(a1), wrap(a2) and C++17 Fold Expressions (args + ...) | Unpacks slice elements as-is only | Unpacks 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, andva_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 aninitializer_listare alwaysconst. - Provides
.begin()and.end()member functions, allowing traversal via rangeforloops.
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++.
Exception Handling#
| Feature | Python | C++ |
|---|---|---|
| Syntax | try - except - else - finally | try - catch (No finally; relies on RAII) |
| Throwable Types | Must derive from BaseException | Any type (primitives like int, strings, class objects) |
| Catch-all | except: or except Exception: | catch (...) (Ellipsis) |
| Uncaught Exception | Prints traceback and exits interpreter | Propagates up call stack; calls std::terminate() $\rightarrow$ abort() |
| Resource Cleanup | finally block, with statement (Context Manager) | RAII (local destructors automatically invoked during stack unwinding) |
| Idiom / Philosophy | EAFP (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).
elseblock: Executes only if no exception was raised in thetryblock.finallyblock: Always executes regardless of whether an exception occurred or was handled; commonly used for cleanup.withstatement (Context Manager): Safely releases resources via__enter__and__exit__even if exceptions occur.- All exception objects must derive from
BaseException(typically subclassingException).
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
tryblock’scatchclauses 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 invokesstd::terminate(), which by default callsabort()to immediately terminate the program. - RAII Instead of
finally: C++ lacks afinallyblock. 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 fromstd::exceptionand 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;
}