From 7967cb5f2e1d5ae41b5c879a417d6cea8a57b768 Mon Sep 17 00:00:00 2001 From: JalonSolov Date: Sat, 31 Jan 2026 23:35:04 -0500 Subject: [PATCH] add more Go idioms --- .gitignore | 1 + idioms/001a/001a.go | 88 ++++++++++++ .../001a_print_hello_world.go | 7 + idioms/001b/001b.go | 67 +++++++++ .../001b_print_hello_world.go | 2 + idioms/002a/002a.go | 103 ++++++++++++++ .../002a_print_hello_10_times.go | 11 ++ idioms/002b/002b.go | 93 +++++++++++++ .../002b_print_hello_10_times.go | 10 ++ idioms/003a/003a.go | 111 +++++++++++++++ .../003a_create_a_procedure.go | 11 ++ idioms/003b/003b.go | 91 +++++++++++++ .../003b_create_a_procedure.go | 12 ++ idioms/004/004.go | 96 +++++++++++++ .../004_create_a_function.go | 14 ++ idioms/005/005.go | 104 ++++++++++++++ .../005_create_a_2d_point_data_structure.go | 25 ++++ idioms/006/006.go | 107 +++++++++++++++ .../006_iterate_over_list_values.go | 17 +++ idioms/007/007.go | 107 +++++++++++++++ ...07_iterate_over_list_indexes_and_values.go | 15 ++ idioms/008/008.go | 128 ++++++++++++++++++ ..._initialize_a_new_map_associative_array.go | 9 ++ idioms/009/009.go | 118 ++++++++++++++++ ...009_create_a_binary_tree_data_structure.go | 31 +++++ idioms/010a/010a.go | 122 +++++++++++++++++ .../010a_shuffle_a_list.go | 17 +++ .../010b_shuffle_a_list.go | 18 +++ .../010c_shuffle_a_list.go | 16 +++ .../010d_shuffle_a_list.go | 17 +++ .../011a_pick_a_random_element_from_a_list.go | 12 ++ .../012_check_if_list_contains_a_value.go | 20 +++ .../013_iterate_over_map_keys_and_values.go | 16 +++ ...y_a_random_floating_point_number_in_a_b.go | 15 ++ ..._pick_uniformly_a_random_integer_in_a_b.go | 17 +++ ...depth_first_traversing_of_a_binary_tree.go | 51 +++++++ .../017_create_a_tree_data_structure.go | 42 ++++++ .../018_depth_first_traversing_of_a_tree.go | 41 ++++++ .../019_reverse_a_list/019_reverse_a_list.go | 14 ++ .../020_return_two_values.go | 19 +++ idioms/021_swap_values/021_swap_values.go | 11 ++ .../022a_convert_string_to_integer.go | 22 +++ .../022b_convert_string_to_integer.go | 19 +++ ..._number_to_string_with_2_decimal_places.go | 9 ++ ...japanese_word_\343\203\215\343\202\263.go" | 8 ++ .../025_send_a_value_to_another_thread.go | 20 +++ .../026a_create_a_2_dimensional_array.go | 11 ++ .../026b_create_a_2_dimensional_array.go | 21 +++ .../027a_create_a_3_dimensional_array.go | 16 +++ .../027b_create_a_3_dimensional_array.go | 24 ++++ .../028a_sort_by_a_property.go | 34 +++++ .../028b_sort_by_a_property.go | 28 ++++ .../029_remove_item_from_list_by_its_index.go | 14 ++ ...ize_execution_of_1000_independent_tasks.go | 21 +++ .../031_recursive_factorial_simple.go | 18 +++ .../032_integer_exponentiation_by_squaring.go | 20 +++ ...irst_class_function_generic_composition.go | 23 ++++ idioms/037_currying/037_currying.go | 56 ++++++++ .../039_check_if_string_contains_a_word.go | 22 +++ .../042_continue_outer_loop.go | 21 +++ .../043_break_outer_loop.go | 26 ++++ .../044_insert_element_in_list.go | 19 +++ .../045_pause_execution_for_5_seconds.go | 11 ++ .../048_multi_line_string_literal.go | 13 ++ .../049a_split_a_space_separated_string.go | 23 ++++ .../049b_split_a_space_separated_string.go | 23 ++++ .../050_make_an_infinite_loop.go | 14 ++ .../051_check_if_map_contains_key.go | 21 +++ .../053_join_a_list_of_strings.go | 14 ++ .../054_compute_sum_of_integers.go | 12 ++ .../055a_convert_integer_to_string.go | 12 ++ .../055b_convert_integer_to_string.go | 12 ++ .../055c_convert_integer_to_string.go | 18 +++ ..._parallel_tasks_and_wait_for_completion.go | 27 ++++ .../058_extract_file_content_to_a_string.go | 25 ++++ .../059_write_to_standard_error_stream.go | 11 ++ .../061_get_current_date.go | 12 ++ .../062_find_substring_position.go | 22 +++ .../063_replace_fragment_of_a_string.go | 14 ++ .../065_format_decimal_number.go | 9 ++ .../066_big_integer_exponentiation.go | 18 +++ .../068b_create_a_bitset.go | 17 +++ .../068c_create_a_bitset.go | 43 ++++++ .../069a_seed_random_generator.go | 12 ++ .../069b_seed_random_generator.go | 12 ++ ...070a_use_clock_as_random_generator_seed.go | 15 ++ ...070b_use_clock_as_random_generator_seed.go | 15 ++ .../071_echo_program_implementation.go | 9 ++ .../073_create_a_factory.go | 21 +++ .../076a_binary_digits_from_an_integer.go | 11 ++ .../076b_binary_digits_from_an_integer.go | 13 ++ .../078a_do_while_loop/078a_do_while_loop.go | 21 +++ .../078b_do_while_loop/078b_do_while_loop.go | 18 +++ ...onvert_integer_to_floating_point_number.go | 15 ++ ...uncate_floating_point_number_to_integer.go | 12 ++ ..._round_floating_point_number_to_integer.go | 17 +++ .../082_count_substring_occurrences.go | 15 ++ .../083_regex_with_character_repetition.go | 23 ++++ ...ts_set_in_integer_binary_representation.go | 37 +++++ ...ts_set_in_integer_binary_representation.go | 13 ++ ...check_if_integer_addition_will_overflow.go | 24 ++++ idioms/087_stop_program/087_stop_program.go | 12 ++ .../088_allocate_1m_bytes.go | 14 ++ .../089_handle_invalid_argument.go | 33 +++++ .../091a_load_json_file_into_object.go | 46 +++++++ .../091b_load_json_file_into_object.go | 50 +++++++ .../092_save_object_into_json_file.go | 33 +++++ ..._pass_a_runnable_procedure_as_parameter.go | 17 +++ .../094a_print_type_of_variable.go | 20 +++ .../094b_print_type_of_variable.go | 22 +++ idioms/095_get_file_size/095_get_file_size.go | 34 +++++ .../098_epoch_seconds_to_date_object.go | 13 ++ .../099_format_date_yyyy_mm_dd.go | 14 ++ .../100a_sort_by_a_comparator.go | 39 ++++++ .../100b_sort_by_a_comparator.go | 45 ++++++ .../100c_sort_by_a_comparator.go | 32 +++++ ...oad_from_http_get_request_into_a_string.go | 45 ++++++ ..._load_from_http_get_request_into_a_file.go | 79 +++++++++++ .../103_load_xml_file_into_struct.go | 49 +++++++ .../104_save_object_into_xml_file.go | 41 ++++++ .../105_current_executable_name.go | 16 +++ .../106_get_program_working_directory.go | 11 ++ ...7_get_folder_containing_current_program.go | 20 +++ .../110_check_if_string_is_blank.go | 24 ++++ .../111_launch_other_program.go | 11 ++ ...terate_over_map_entries_ordered_by_keys.go | 26 ++++ ...rate_over_map_entries_ordered_by_values.go | 37 +++++ ...rate_over_map_entries_ordered_by_values.go | 34 +++++ idioms/115_compare_dates/115_compare_dates.go | 15 ++ ..._remove_occurrences_of_word_from_string.go | 13 ++ ..._remove_occurrences_of_word_from_string.go | 13 ++ idioms/117_get_list_size/117_get_list_size.go | 15 ++ idioms/118_list_to_set/118_list_to_set.go | 15 ++ .../119a_deduplicate_list.go | 24 ++++ .../119b_deduplicate_list.go | 22 +++ .../120a_read_integer_from_stdin.go | 38 ++++++ .../120b_read_integer_from_stdin.go | 37 +++++ .../122_declare_enumeration.go | 18 +++ .../123_assert_condition.go | 29 ++++ ...nary_search_for_a_value_in_sorted_array.go | 26 ++++ .../125a_measure_function_call_duration.go | 20 +++ .../125b_measure_function_call_duration.go | 18 +++ .../126_multiple_return_values.go | 14 ++ .../128_breadth_first_traversing_of_a_tree.go | 47 +++++++ .../131_successive_conditions.go | 42 ++++++ ...measure_duration_of_procedure_execution.go | 27 ++++ .../133_case_insensitive_string_contains.go | 30 ++++ .../135_remove_item_from_list_by_its_value.go | 19 +++ ...7a_check_if_string_contains_only_digits.go | 25 ++++ ...7b_check_if_string_contains_only_digits.go | 21 +++ .../138_create_temp_file.go | 36 +++++ .../139_create_temp_directory.go | 37 +++++ .../140_delete_map_entry.go | 18 +++ .../141_iterate_in_sequence_over_two_lists.go | 17 +++ .../142a_hexadecimal_digits_of_an_integer.go | 11 ++ .../142b_hexadecimal_digits_of_an_integer.go | 13 ++ ...43_iterate_alternatively_over_two_lists.go | 19 +++ .../144_check_if_file_exists.go | 23 ++++ .../145_print_log_line_with_datetime.go | 12 ++ ...convert_string_to_floating_point_number.go | 17 +++ .../147a_remove_all_non_ascii_characters.go | 15 ++ .../147b_remove_all_non_ascii_characters.go | 18 +++ .../148_read_list_of_integers_from_stdin.go | 31 +++++ .../150_remove_trailing_slash.go | 14 ++ ...a_remove_string_trailing_path_separator.go | 27 ++++ ...b_remove_string_trailing_path_separator.go | 28 ++++ .../152_turn_a_character_into_a_string.go | 14 ++ .../153a_concatenate_string_with_integer.go | 14 ++ .../153b_concatenate_string_with_integer.go | 15 ++ ...54a_halfway_between_two_hex_color_codes.go | 55 ++++++++ ...54b_halfway_between_two_hex_color_codes.go | 55 ++++++++ idioms/155_delete_file/155_delete_file.go | 29 ++++ .../156_format_integer_with_zero_padding.go | 18 +++ .../157_declare_constant_string.go | 11 ++ .../158_random_sublist/158_random_sublist.go | 21 +++ ...161_multiply_all_the_elements_of_a_list.go | 16 +++ ...execute_procedures_depending_on_options.go | 36 +++++ .../163_print_list_elements_by_group_of_2.go | 13 ++ .../165_last_element_of_list.go | 13 ++ .../166a_concatenate_two_lists.go | 14 ++ .../166b_concatenate_two_lists.go | 17 +++ .../166c_concatenate_two_lists.go | 18 +++ idioms/167_trim_prefix/167_trim_prefix.go | 15 ++ idioms/168_trim_suffix/168_trim_suffix.go | 15 ++ idioms/169_string_length/169_string_length.go | 11 ++ idioms/170_get_map_size/170_get_map_size.go | 9 ++ ...171_add_an_element_at_the_end_of_a_list.go | 12 ++ .../172_insert_an_entry_in_a_map.go | 13 ++ .../174a_make_http_post_request.go | 56 ++++++++ .../174b_make_http_post_request.go | 57 ++++++++ .../175a_bytes_to_hex_string.go | 14 ++ .../175b_bytes_to_hex_string.go | 13 ++ .../176_hex_string_to_byte_array.go | 19 +++ ...ith_a_given_list_of_filename_extensions.go | 76 +++++++++++ .../178_check_if_point_is_inside_rectangle.go | 21 +++ .../180_list_files_in_directory.go | 20 +++ idioms/182_quine_program/182_quine_program.go | 17 +++ .../183_make_http_put_request.go | 67 +++++++++ idioms/184_tomorrow/184_tomorrow.go | 15 ++ .../185a_execute_function_in_30_seconds.go | 27 ++++ .../185b_execute_function_in_30_seconds.go | 23 ++++ .../186a_exit_program_cleanly.go | 12 ++ .../186b_exit_program_cleanly.go | 28 ++++ .../189_filter_and_transform_list.go | 30 ++++ ..._value_in_a_list_is_larger_than_a_limit.go | 20 +++ ...a_real_variable_with_at_least_20_digits.go | 15 ++ .../197_get_a_list_of_lines_from_a_file.go | 38 ++++++ ..._program_execution_with_error_condition.go | 10 ++ ...ate_a_file_at_the_current_file_position.go | 32 +++++ .../202_sum_of_squares/202_sum_of_squares.go | 14 ++ ..._fraction_and_exponent_of_a_real_number.go | 12 ++ .../205a_get_an_environment_variable.go | 15 ++ .../205b_get_an_environment_variable.go | 15 ++ .../206_switch_statement_with_strings.go | 36 +++++ .../208_formula_with_arrays.go | 24 ++++ ...9_type_with_automatic_deep_deallocation.go | 22 +++ .../210_compiler_version_and_options.go | 9 ++ .../211a_create_folder/211a_create_folder.go | 23 ++++ .../211b_create_folder/211b_create_folder.go | 32 +++++ .../212_check_if_folder_exists.go | 22 +++ .../214_pad_string_on_the_right.go | 25 ++++ .../215_pad_string_on_the_left.go | 25 ++++ ...place_multiple_spaces_with_single_space.go | 20 +++ .../220b_create_a_tuple_value.go | 16 +++ .../221_remove_all_non_digits_characters.go | 15 ++ ...d_the_first_index_of_an_element_in_list.go | 20 +++ idioms/223_for_else_loop/223_for_else_loop.go | 20 +++ ...25_declare_and_use_an_optional_argument.go | 14 ++ .../226_delete_last_element_from_list.go | 13 ++ idioms/227_copy_list/227_copy_list.go | 19 +++ idioms/228a_copy_a_file/228a_copy_a_file.go | 43 ++++++ idioms/228b_copy_a_file/228b_copy_a_file.go | 51 +++++++ idioms/228c_copy_a_file/228c_copy_a_file.go | 58 ++++++++ .../229_cancel_an_operation.go | 27 ++++ idioms/230_timeout/230_timeout.go | 25 ++++ ..._test_if_bytes_are_a_valid_utf_8_string.go | 19 +++ .../232_read_a_command_line_boolean_flag.go | 22 +++ .../233_read_a_command_line_string_flag.go | 19 +++ .../234_encode_bytes_to_base64.go | 12 ++ idioms/235_decode_base64/235_decode_base64.go | 18 +++ .../236c_large_quotient.go | 15 ++ idioms/237a_xor_integers/237a_xor_integers.go | 15 ++ .../238a_xor_byte_arrays.go | 20 +++ ...239_find_first_regular_expression_match.go | 21 +++ .../241_yield_priority_to_other_threads.go | 24 ++++ idioms/243_print_list/243_print_list.go | 40 ++++++ idioms/244a_print_map/244a_print_map.go | 24 ++++ idioms/244b_print_map/244b_print_map.go | 14 ++ .../245_print_value_of_custom_type.go | 44 ++++++ .../246_count_distinct_elements.go | 19 +++ ...9_declare_and_assign_multiple_variables.go | 14 ++ .../251_parse_binary_digits.go | 19 +++ .../252_conditional_assignment.go | 20 +++ .../253_print_stack_trace.go | 16 +++ .../254_replace_value_in_list.go | 22 +++ .../256_count_backwards.go | 11 ++ .../257_traverse_list_backwards.go | 16 +++ ...ert_list_of_strings_to_list_of_integers.go | 21 +++ .../259_split_on_several_separators.go | 15 ++ .../260_create_an_empty_list_of_strings.go | 17 +++ .../261_format_time_hours_minutes_seconds.go | 14 ++ .../262_count_trailing_zero_bits.go | 14 ++ .../266_repeated_string.go | 15 ++ ...ing_to_argument_that_can_be_of_any_type.go | 18 +++ .../273_check_if_folder_is_empty.go | 62 +++++++++ .../274_remove_all_white_space_characters.go | 26 ++++ .../275_binary_digits_to_byte_array.go | 28 ++++ ...8_read_one_line_from_the_standard_input.go | 33 +++++ ...list_of_strings_from_the_standard_input.go | 38 ++++++ idioms/280_filter_map/280_filter_map.go | 35 +++++ .../282_use_a_custom_type_as_map_key.go | 16 +++ ...83_split_with_a_custom_string_separator.go | 16 +++ .../284_created_a_zeroed_list_of_integers.go | 11 ++ ...286_iterate_over_characters_of_a_string.go | 13 ++ .../287_number_of_bytes_of_a_string.go | 11 ++ .../289_concatenate_two_strings.go | 13 ++ idioms/290_sort_sublist/290_sort_sublist.go | 35 +++++ ..._in_chinese_to_standard_output_in_utf_8.go | 7 + 278 files changed, 7194 insertions(+) create mode 100644 idioms/001a/001a.go create mode 100644 idioms/001a_print_hello_world/001a_print_hello_world.go create mode 100644 idioms/001b/001b.go create mode 100644 idioms/001b_print_hello_world/001b_print_hello_world.go create mode 100644 idioms/002a/002a.go create mode 100644 idioms/002a_print_hello_10_times/002a_print_hello_10_times.go create mode 100644 idioms/002b/002b.go create mode 100644 idioms/002b_print_hello_10_times/002b_print_hello_10_times.go create mode 100644 idioms/003a/003a.go create mode 100644 idioms/003a_create_a_procedure/003a_create_a_procedure.go create mode 100644 idioms/003b/003b.go create mode 100644 idioms/003b_create_a_procedure/003b_create_a_procedure.go create mode 100644 idioms/004/004.go create mode 100644 idioms/004_create_a_function/004_create_a_function.go create mode 100644 idioms/005/005.go create mode 100644 idioms/005_create_a_2d_point_data_structure/005_create_a_2d_point_data_structure.go create mode 100644 idioms/006/006.go create mode 100644 idioms/006_iterate_over_list_values/006_iterate_over_list_values.go create mode 100644 idioms/007/007.go create mode 100644 idioms/007_iterate_over_list_indexes_and_values/007_iterate_over_list_indexes_and_values.go create mode 100644 idioms/008/008.go create mode 100644 idioms/008_initialize_a_new_map_associative_array/008_initialize_a_new_map_associative_array.go create mode 100644 idioms/009/009.go create mode 100644 idioms/009_create_a_binary_tree_data_structure/009_create_a_binary_tree_data_structure.go create mode 100644 idioms/010a/010a.go create mode 100644 idioms/010a_shuffle_a_list/010a_shuffle_a_list.go create mode 100644 idioms/010b_shuffle_a_list/010b_shuffle_a_list.go create mode 100644 idioms/010c_shuffle_a_list/010c_shuffle_a_list.go create mode 100644 idioms/010d_shuffle_a_list/010d_shuffle_a_list.go create mode 100644 idioms/011a_pick_a_random_element_from_a_list/011a_pick_a_random_element_from_a_list.go create mode 100644 idioms/012_check_if_list_contains_a_value/012_check_if_list_contains_a_value.go create mode 100644 idioms/013_iterate_over_map_keys_and_values/013_iterate_over_map_keys_and_values.go create mode 100644 idioms/014_pick_uniformly_a_random_floating_point_number_in_a_b/014_pick_uniformly_a_random_floating_point_number_in_a_b.go create mode 100644 idioms/015_pick_uniformly_a_random_integer_in_a_b/015_pick_uniformly_a_random_integer_in_a_b.go create mode 100644 idioms/016_depth_first_traversing_of_a_binary_tree/016_depth_first_traversing_of_a_binary_tree.go create mode 100644 idioms/017_create_a_tree_data_structure/017_create_a_tree_data_structure.go create mode 100644 idioms/018_depth_first_traversing_of_a_tree/018_depth_first_traversing_of_a_tree.go create mode 100644 idioms/019_reverse_a_list/019_reverse_a_list.go create mode 100644 idioms/020_return_two_values/020_return_two_values.go create mode 100644 idioms/021_swap_values/021_swap_values.go create mode 100644 idioms/022a_convert_string_to_integer/022a_convert_string_to_integer.go create mode 100644 idioms/022b_convert_string_to_integer/022b_convert_string_to_integer.go create mode 100644 idioms/023_convert_real_number_to_string_with_2_decimal_places/023_convert_real_number_to_string_with_2_decimal_places.go create mode 100644 "idioms/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263.go" create mode 100644 idioms/025_send_a_value_to_another_thread/025_send_a_value_to_another_thread.go create mode 100644 idioms/026a_create_a_2_dimensional_array/026a_create_a_2_dimensional_array.go create mode 100644 idioms/026b_create_a_2_dimensional_array/026b_create_a_2_dimensional_array.go create mode 100644 idioms/027a_create_a_3_dimensional_array/027a_create_a_3_dimensional_array.go create mode 100644 idioms/027b_create_a_3_dimensional_array/027b_create_a_3_dimensional_array.go create mode 100644 idioms/028a_sort_by_a_property/028a_sort_by_a_property.go create mode 100644 idioms/028b_sort_by_a_property/028b_sort_by_a_property.go create mode 100644 idioms/029_remove_item_from_list_by_its_index/029_remove_item_from_list_by_its_index.go create mode 100644 idioms/030_parallelize_execution_of_1000_independent_tasks/030_parallelize_execution_of_1000_independent_tasks.go create mode 100644 idioms/031_recursive_factorial_simple/031_recursive_factorial_simple.go create mode 100644 idioms/032_integer_exponentiation_by_squaring/032_integer_exponentiation_by_squaring.go create mode 100644 idioms/036_first_class_function_generic_composition/036_first_class_function_generic_composition.go create mode 100644 idioms/037_currying/037_currying.go create mode 100644 idioms/039_check_if_string_contains_a_word/039_check_if_string_contains_a_word.go create mode 100644 idioms/042_continue_outer_loop/042_continue_outer_loop.go create mode 100644 idioms/043_break_outer_loop/043_break_outer_loop.go create mode 100644 idioms/044_insert_element_in_list/044_insert_element_in_list.go create mode 100644 idioms/045_pause_execution_for_5_seconds/045_pause_execution_for_5_seconds.go create mode 100644 idioms/048_multi_line_string_literal/048_multi_line_string_literal.go create mode 100644 idioms/049a_split_a_space_separated_string/049a_split_a_space_separated_string.go create mode 100644 idioms/049b_split_a_space_separated_string/049b_split_a_space_separated_string.go create mode 100644 idioms/050_make_an_infinite_loop/050_make_an_infinite_loop.go create mode 100644 idioms/051_check_if_map_contains_key/051_check_if_map_contains_key.go create mode 100644 idioms/053_join_a_list_of_strings/053_join_a_list_of_strings.go create mode 100644 idioms/054_compute_sum_of_integers/054_compute_sum_of_integers.go create mode 100644 idioms/055a_convert_integer_to_string/055a_convert_integer_to_string.go create mode 100644 idioms/055b_convert_integer_to_string/055b_convert_integer_to_string.go create mode 100644 idioms/055c_convert_integer_to_string/055c_convert_integer_to_string.go create mode 100644 idioms/056_launch_1000_parallel_tasks_and_wait_for_completion/056_launch_1000_parallel_tasks_and_wait_for_completion.go create mode 100644 idioms/058_extract_file_content_to_a_string/058_extract_file_content_to_a_string.go create mode 100644 idioms/059_write_to_standard_error_stream/059_write_to_standard_error_stream.go create mode 100644 idioms/061_get_current_date/061_get_current_date.go create mode 100644 idioms/062_find_substring_position/062_find_substring_position.go create mode 100644 idioms/063_replace_fragment_of_a_string/063_replace_fragment_of_a_string.go create mode 100644 idioms/065_format_decimal_number/065_format_decimal_number.go create mode 100644 idioms/066_big_integer_exponentiation/066_big_integer_exponentiation.go create mode 100644 idioms/068b_create_a_bitset/068b_create_a_bitset.go create mode 100644 idioms/068c_create_a_bitset/068c_create_a_bitset.go create mode 100644 idioms/069a_seed_random_generator/069a_seed_random_generator.go create mode 100644 idioms/069b_seed_random_generator/069b_seed_random_generator.go create mode 100644 idioms/070a_use_clock_as_random_generator_seed/070a_use_clock_as_random_generator_seed.go create mode 100644 idioms/070b_use_clock_as_random_generator_seed/070b_use_clock_as_random_generator_seed.go create mode 100644 idioms/071_echo_program_implementation/071_echo_program_implementation.go create mode 100644 idioms/073_create_a_factory/073_create_a_factory.go create mode 100644 idioms/076a_binary_digits_from_an_integer/076a_binary_digits_from_an_integer.go create mode 100644 idioms/076b_binary_digits_from_an_integer/076b_binary_digits_from_an_integer.go create mode 100644 idioms/078a_do_while_loop/078a_do_while_loop.go create mode 100644 idioms/078b_do_while_loop/078b_do_while_loop.go create mode 100644 idioms/079_convert_integer_to_floating_point_number/079_convert_integer_to_floating_point_number.go create mode 100644 idioms/080_truncate_floating_point_number_to_integer/080_truncate_floating_point_number_to_integer.go create mode 100644 idioms/081_round_floating_point_number_to_integer/081_round_floating_point_number_to_integer.go create mode 100644 idioms/082_count_substring_occurrences/082_count_substring_occurrences.go create mode 100644 idioms/083_regex_with_character_repetition/083_regex_with_character_repetition.go create mode 100644 idioms/084a_count_bits_set_in_integer_binary_representation/084a_count_bits_set_in_integer_binary_representation.go create mode 100644 idioms/084b_count_bits_set_in_integer_binary_representation/084b_count_bits_set_in_integer_binary_representation.go create mode 100644 idioms/085_check_if_integer_addition_will_overflow/085_check_if_integer_addition_will_overflow.go create mode 100644 idioms/087_stop_program/087_stop_program.go create mode 100644 idioms/088_allocate_1m_bytes/088_allocate_1m_bytes.go create mode 100644 idioms/089_handle_invalid_argument/089_handle_invalid_argument.go create mode 100644 idioms/091a_load_json_file_into_object/091a_load_json_file_into_object.go create mode 100644 idioms/091b_load_json_file_into_object/091b_load_json_file_into_object.go create mode 100644 idioms/092_save_object_into_json_file/092_save_object_into_json_file.go create mode 100644 idioms/093_pass_a_runnable_procedure_as_parameter/093_pass_a_runnable_procedure_as_parameter.go create mode 100644 idioms/094a_print_type_of_variable/094a_print_type_of_variable.go create mode 100644 idioms/094b_print_type_of_variable/094b_print_type_of_variable.go create mode 100644 idioms/095_get_file_size/095_get_file_size.go create mode 100644 idioms/098_epoch_seconds_to_date_object/098_epoch_seconds_to_date_object.go create mode 100644 idioms/099_format_date_yyyy_mm_dd/099_format_date_yyyy_mm_dd.go create mode 100644 idioms/100a_sort_by_a_comparator/100a_sort_by_a_comparator.go create mode 100644 idioms/100b_sort_by_a_comparator/100b_sort_by_a_comparator.go create mode 100644 idioms/100c_sort_by_a_comparator/100c_sort_by_a_comparator.go create mode 100644 idioms/101_load_from_http_get_request_into_a_string/101_load_from_http_get_request_into_a_string.go create mode 100644 idioms/102_load_from_http_get_request_into_a_file/102_load_from_http_get_request_into_a_file.go create mode 100644 idioms/103_load_xml_file_into_struct/103_load_xml_file_into_struct.go create mode 100644 idioms/104_save_object_into_xml_file/104_save_object_into_xml_file.go create mode 100644 idioms/105_current_executable_name/105_current_executable_name.go create mode 100644 idioms/106_get_program_working_directory/106_get_program_working_directory.go create mode 100644 idioms/107_get_folder_containing_current_program/107_get_folder_containing_current_program.go create mode 100644 idioms/110_check_if_string_is_blank/110_check_if_string_is_blank.go create mode 100644 idioms/111_launch_other_program/111_launch_other_program.go create mode 100644 idioms/112_iterate_over_map_entries_ordered_by_keys/112_iterate_over_map_entries_ordered_by_keys.go create mode 100644 idioms/113a_iterate_over_map_entries_ordered_by_values/113a_iterate_over_map_entries_ordered_by_values.go create mode 100644 idioms/113b_iterate_over_map_entries_ordered_by_values/113b_iterate_over_map_entries_ordered_by_values.go create mode 100644 idioms/115_compare_dates/115_compare_dates.go create mode 100644 idioms/116a_remove_occurrences_of_word_from_string/116a_remove_occurrences_of_word_from_string.go create mode 100644 idioms/116b_remove_occurrences_of_word_from_string/116b_remove_occurrences_of_word_from_string.go create mode 100644 idioms/117_get_list_size/117_get_list_size.go create mode 100644 idioms/118_list_to_set/118_list_to_set.go create mode 100644 idioms/119a_deduplicate_list/119a_deduplicate_list.go create mode 100644 idioms/119b_deduplicate_list/119b_deduplicate_list.go create mode 100644 idioms/120a_read_integer_from_stdin/120a_read_integer_from_stdin.go create mode 100644 idioms/120b_read_integer_from_stdin/120b_read_integer_from_stdin.go create mode 100644 idioms/122_declare_enumeration/122_declare_enumeration.go create mode 100644 idioms/123_assert_condition/123_assert_condition.go create mode 100644 idioms/124b_binary_search_for_a_value_in_sorted_array/124b_binary_search_for_a_value_in_sorted_array.go create mode 100644 idioms/125a_measure_function_call_duration/125a_measure_function_call_duration.go create mode 100644 idioms/125b_measure_function_call_duration/125b_measure_function_call_duration.go create mode 100644 idioms/126_multiple_return_values/126_multiple_return_values.go create mode 100644 idioms/128_breadth_first_traversing_of_a_tree/128_breadth_first_traversing_of_a_tree.go create mode 100644 idioms/131_successive_conditions/131_successive_conditions.go create mode 100644 idioms/132_measure_duration_of_procedure_execution/132_measure_duration_of_procedure_execution.go create mode 100644 idioms/133_case_insensitive_string_contains/133_case_insensitive_string_contains.go create mode 100644 idioms/135_remove_item_from_list_by_its_value/135_remove_item_from_list_by_its_value.go create mode 100644 idioms/137a_check_if_string_contains_only_digits/137a_check_if_string_contains_only_digits.go create mode 100644 idioms/137b_check_if_string_contains_only_digits/137b_check_if_string_contains_only_digits.go create mode 100644 idioms/138_create_temp_file/138_create_temp_file.go create mode 100644 idioms/139_create_temp_directory/139_create_temp_directory.go create mode 100644 idioms/140_delete_map_entry/140_delete_map_entry.go create mode 100644 idioms/141_iterate_in_sequence_over_two_lists/141_iterate_in_sequence_over_two_lists.go create mode 100644 idioms/142a_hexadecimal_digits_of_an_integer/142a_hexadecimal_digits_of_an_integer.go create mode 100644 idioms/142b_hexadecimal_digits_of_an_integer/142b_hexadecimal_digits_of_an_integer.go create mode 100644 idioms/143_iterate_alternatively_over_two_lists/143_iterate_alternatively_over_two_lists.go create mode 100644 idioms/144_check_if_file_exists/144_check_if_file_exists.go create mode 100644 idioms/145_print_log_line_with_datetime/145_print_log_line_with_datetime.go create mode 100644 idioms/146_convert_string_to_floating_point_number/146_convert_string_to_floating_point_number.go create mode 100644 idioms/147a_remove_all_non_ascii_characters/147a_remove_all_non_ascii_characters.go create mode 100644 idioms/147b_remove_all_non_ascii_characters/147b_remove_all_non_ascii_characters.go create mode 100644 idioms/148_read_list_of_integers_from_stdin/148_read_list_of_integers_from_stdin.go create mode 100644 idioms/150_remove_trailing_slash/150_remove_trailing_slash.go create mode 100644 idioms/151a_remove_string_trailing_path_separator/151a_remove_string_trailing_path_separator.go create mode 100644 idioms/151b_remove_string_trailing_path_separator/151b_remove_string_trailing_path_separator.go create mode 100644 idioms/152_turn_a_character_into_a_string/152_turn_a_character_into_a_string.go create mode 100644 idioms/153a_concatenate_string_with_integer/153a_concatenate_string_with_integer.go create mode 100644 idioms/153b_concatenate_string_with_integer/153b_concatenate_string_with_integer.go create mode 100644 idioms/154a_halfway_between_two_hex_color_codes/154a_halfway_between_two_hex_color_codes.go create mode 100644 idioms/154b_halfway_between_two_hex_color_codes/154b_halfway_between_two_hex_color_codes.go create mode 100644 idioms/155_delete_file/155_delete_file.go create mode 100644 idioms/156_format_integer_with_zero_padding/156_format_integer_with_zero_padding.go create mode 100644 idioms/157_declare_constant_string/157_declare_constant_string.go create mode 100644 idioms/158_random_sublist/158_random_sublist.go create mode 100644 idioms/161_multiply_all_the_elements_of_a_list/161_multiply_all_the_elements_of_a_list.go create mode 100644 idioms/162_execute_procedures_depending_on_options/162_execute_procedures_depending_on_options.go create mode 100644 idioms/163_print_list_elements_by_group_of_2/163_print_list_elements_by_group_of_2.go create mode 100644 idioms/165_last_element_of_list/165_last_element_of_list.go create mode 100644 idioms/166a_concatenate_two_lists/166a_concatenate_two_lists.go create mode 100644 idioms/166b_concatenate_two_lists/166b_concatenate_two_lists.go create mode 100644 idioms/166c_concatenate_two_lists/166c_concatenate_two_lists.go create mode 100644 idioms/167_trim_prefix/167_trim_prefix.go create mode 100644 idioms/168_trim_suffix/168_trim_suffix.go create mode 100644 idioms/169_string_length/169_string_length.go create mode 100644 idioms/170_get_map_size/170_get_map_size.go create mode 100644 idioms/171_add_an_element_at_the_end_of_a_list/171_add_an_element_at_the_end_of_a_list.go create mode 100644 idioms/172_insert_an_entry_in_a_map/172_insert_an_entry_in_a_map.go create mode 100644 idioms/174a_make_http_post_request/174a_make_http_post_request.go create mode 100644 idioms/174b_make_http_post_request/174b_make_http_post_request.go create mode 100644 idioms/175a_bytes_to_hex_string/175a_bytes_to_hex_string.go create mode 100644 idioms/175b_bytes_to_hex_string/175b_bytes_to_hex_string.go create mode 100644 idioms/176_hex_string_to_byte_array/176_hex_string_to_byte_array.go create mode 100644 idioms/177_find_files_with_a_given_list_of_filename_extensions/177_find_files_with_a_given_list_of_filename_extensions.go create mode 100644 idioms/178_check_if_point_is_inside_rectangle/178_check_if_point_is_inside_rectangle.go create mode 100644 idioms/180_list_files_in_directory/180_list_files_in_directory.go create mode 100644 idioms/182_quine_program/182_quine_program.go create mode 100644 idioms/183_make_http_put_request/183_make_http_put_request.go create mode 100644 idioms/184_tomorrow/184_tomorrow.go create mode 100644 idioms/185a_execute_function_in_30_seconds/185a_execute_function_in_30_seconds.go create mode 100644 idioms/185b_execute_function_in_30_seconds/185b_execute_function_in_30_seconds.go create mode 100644 idioms/186a_exit_program_cleanly/186a_exit_program_cleanly.go create mode 100644 idioms/186b_exit_program_cleanly/186b_exit_program_cleanly.go create mode 100644 idioms/189_filter_and_transform_list/189_filter_and_transform_list.go create mode 100644 idioms/191_check_if_any_value_in_a_list_is_larger_than_a_limit/191_check_if_any_value_in_a_list_is_larger_than_a_limit.go create mode 100644 idioms/192_declare_a_real_variable_with_at_least_20_digits/192_declare_a_real_variable_with_at_least_20_digits.go create mode 100644 idioms/197_get_a_list_of_lines_from_a_file/197_get_a_list_of_lines_from_a_file.go create mode 100644 idioms/198_abort_program_execution_with_error_condition/198_abort_program_execution_with_error_condition.go create mode 100644 idioms/199_truncate_a_file_at_the_current_file_position/199_truncate_a_file_at_the_current_file_position.go create mode 100644 idioms/202_sum_of_squares/202_sum_of_squares.go create mode 100644 idioms/204_return_fraction_and_exponent_of_a_real_number/204_return_fraction_and_exponent_of_a_real_number.go create mode 100644 idioms/205a_get_an_environment_variable/205a_get_an_environment_variable.go create mode 100644 idioms/205b_get_an_environment_variable/205b_get_an_environment_variable.go create mode 100644 idioms/206_switch_statement_with_strings/206_switch_statement_with_strings.go create mode 100644 idioms/208_formula_with_arrays/208_formula_with_arrays.go create mode 100644 idioms/209_type_with_automatic_deep_deallocation/209_type_with_automatic_deep_deallocation.go create mode 100644 idioms/210_compiler_version_and_options/210_compiler_version_and_options.go create mode 100644 idioms/211a_create_folder/211a_create_folder.go create mode 100644 idioms/211b_create_folder/211b_create_folder.go create mode 100644 idioms/212_check_if_folder_exists/212_check_if_folder_exists.go create mode 100644 idioms/214_pad_string_on_the_right/214_pad_string_on_the_right.go create mode 100644 idioms/215_pad_string_on_the_left/215_pad_string_on_the_left.go create mode 100644 idioms/219_replace_multiple_spaces_with_single_space/219_replace_multiple_spaces_with_single_space.go create mode 100644 idioms/220b_create_a_tuple_value/220b_create_a_tuple_value.go create mode 100644 idioms/221_remove_all_non_digits_characters/221_remove_all_non_digits_characters.go create mode 100644 idioms/222_find_the_first_index_of_an_element_in_list/222_find_the_first_index_of_an_element_in_list.go create mode 100644 idioms/223_for_else_loop/223_for_else_loop.go create mode 100644 idioms/225_declare_and_use_an_optional_argument/225_declare_and_use_an_optional_argument.go create mode 100644 idioms/226_delete_last_element_from_list/226_delete_last_element_from_list.go create mode 100644 idioms/227_copy_list/227_copy_list.go create mode 100644 idioms/228a_copy_a_file/228a_copy_a_file.go create mode 100644 idioms/228b_copy_a_file/228b_copy_a_file.go create mode 100644 idioms/228c_copy_a_file/228c_copy_a_file.go create mode 100644 idioms/229_cancel_an_operation/229_cancel_an_operation.go create mode 100644 idioms/230_timeout/230_timeout.go create mode 100644 idioms/231_test_if_bytes_are_a_valid_utf_8_string/231_test_if_bytes_are_a_valid_utf_8_string.go create mode 100644 idioms/232_read_a_command_line_boolean_flag/232_read_a_command_line_boolean_flag.go create mode 100644 idioms/233_read_a_command_line_string_flag/233_read_a_command_line_string_flag.go create mode 100644 idioms/234_encode_bytes_to_base64/234_encode_bytes_to_base64.go create mode 100644 idioms/235_decode_base64/235_decode_base64.go create mode 100644 idioms/236c_large_quotient/236c_large_quotient.go create mode 100644 idioms/237a_xor_integers/237a_xor_integers.go create mode 100644 idioms/238a_xor_byte_arrays/238a_xor_byte_arrays.go create mode 100644 idioms/239_find_first_regular_expression_match/239_find_first_regular_expression_match.go create mode 100644 idioms/241_yield_priority_to_other_threads/241_yield_priority_to_other_threads.go create mode 100644 idioms/243_print_list/243_print_list.go create mode 100644 idioms/244a_print_map/244a_print_map.go create mode 100644 idioms/244b_print_map/244b_print_map.go create mode 100644 idioms/245_print_value_of_custom_type/245_print_value_of_custom_type.go create mode 100644 idioms/246_count_distinct_elements/246_count_distinct_elements.go create mode 100644 idioms/249_declare_and_assign_multiple_variables/249_declare_and_assign_multiple_variables.go create mode 100644 idioms/251_parse_binary_digits/251_parse_binary_digits.go create mode 100644 idioms/252_conditional_assignment/252_conditional_assignment.go create mode 100644 idioms/253_print_stack_trace/253_print_stack_trace.go create mode 100644 idioms/254_replace_value_in_list/254_replace_value_in_list.go create mode 100644 idioms/256_count_backwards/256_count_backwards.go create mode 100644 idioms/257_traverse_list_backwards/257_traverse_list_backwards.go create mode 100644 idioms/258_convert_list_of_strings_to_list_of_integers/258_convert_list_of_strings_to_list_of_integers.go create mode 100644 idioms/259_split_on_several_separators/259_split_on_several_separators.go create mode 100644 idioms/260_create_an_empty_list_of_strings/260_create_an_empty_list_of_strings.go create mode 100644 idioms/261_format_time_hours_minutes_seconds/261_format_time_hours_minutes_seconds.go create mode 100644 idioms/262_count_trailing_zero_bits/262_count_trailing_zero_bits.go create mode 100644 idioms/266_repeated_string/266_repeated_string.go create mode 100644 idioms/267_pass_string_to_argument_that_can_be_of_any_type/267_pass_string_to_argument_that_can_be_of_any_type.go create mode 100644 idioms/273_check_if_folder_is_empty/273_check_if_folder_is_empty.go create mode 100644 idioms/274_remove_all_white_space_characters/274_remove_all_white_space_characters.go create mode 100644 idioms/275_binary_digits_to_byte_array/275_binary_digits_to_byte_array.go create mode 100644 idioms/278_read_one_line_from_the_standard_input/278_read_one_line_from_the_standard_input.go create mode 100644 idioms/279_read_list_of_strings_from_the_standard_input/279_read_list_of_strings_from_the_standard_input.go create mode 100644 idioms/280_filter_map/280_filter_map.go create mode 100644 idioms/282_use_a_custom_type_as_map_key/282_use_a_custom_type_as_map_key.go create mode 100644 idioms/283_split_with_a_custom_string_separator/283_split_with_a_custom_string_separator.go create mode 100644 idioms/284_created_a_zeroed_list_of_integers/284_created_a_zeroed_list_of_integers.go create mode 100644 idioms/286_iterate_over_characters_of_a_string/286_iterate_over_characters_of_a_string.go create mode 100644 idioms/287_number_of_bytes_of_a_string/287_number_of_bytes_of_a_string.go create mode 100644 idioms/289_concatenate_two_strings/289_concatenate_two_strings.go create mode 100644 idioms/290_sort_sublist/290_sort_sublist.go create mode 100644 idioms/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8.go diff --git a/.gitignore b/.gitignore index 4901728..8097fb4 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ z out.txt complex_tests/**/*.v complex_tests/**/*.vv +translate_esbuild diff --git a/idioms/001a/001a.go b/idioms/001a/001a.go new file mode 100644 index 0000000..d94747c --- /dev/null +++ b/idioms/001a/001a.go @@ -0,0 +1,88 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Fun struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type Args struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + X X `json:"X"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/001a_print_hello_world/001a_print_hello_world.go b/idioms/001a_print_hello_world/001a_print_hello_world.go new file mode 100644 index 0000000..30ed049 --- /dev/null +++ b/idioms/001a_print_hello_world/001a_print_hello_world.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("Hello World") +} \ No newline at end of file diff --git a/idioms/001b/001b.go b/idioms/001b/001b.go new file mode 100644 index 0000000..87886bb --- /dev/null +++ b/idioms/001b/001b.go @@ -0,0 +1,67 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type Fun struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Args struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + X X `json:"X"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Recv any `json:"Recv"` + Name Name `json:"Name"` + Type0 Type0 `json:"Type"` + Body Body `json:"Body"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/001b_print_hello_world/001b_print_hello_world.go b/idioms/001b_print_hello_world/001b_print_hello_world.go new file mode 100644 index 0000000..06fc1e7 --- /dev/null +++ b/idioms/001b_print_hello_world/001b_print_hello_world.go @@ -0,0 +1,2 @@ +package main +func main(){print("Hello World")} \ No newline at end of file diff --git a/idioms/002a/002a.go b/idioms/002a/002a.go new file mode 100644 index 0000000..109cd5f --- /dev/null +++ b/idioms/002a/002a.go @@ -0,0 +1,103 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type RHS struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Init struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs"` + Tok string `json:"Tok"` + RHS []RHS `json:"Rhs"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Y struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Cond struct { + Type string `json:"_type"` + X X `json:"X"` + Op string `json:"Op"` + Y Y `json:"Y"` +} +type Post struct { + Type string `json:"_type"` + X X `json:"X"` + Tok string `json:"Tok"` +} +type List struct { + Type string `json:"_type"` + Init Init `json:"Init"` + Cond Cond `json:"Cond"` + Post Post `json:"Post"` + Body Body `json:"Body"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/002a_print_hello_10_times/002a_print_hello_10_times.go b/idioms/002a_print_hello_10_times/002a_print_hello_10_times.go new file mode 100644 index 0000000..a81c55d --- /dev/null +++ b/idioms/002a_print_hello_10_times/002a_print_hello_10_times.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" +) + +func main() { + for i := 0; i < 10; i++ { + fmt.Println("Hello") + } +} diff --git a/idioms/002b/002b.go b/idioms/002b/002b.go new file mode 100644 index 0000000..5e48c42 --- /dev/null +++ b/idioms/002b/002b.go @@ -0,0 +1,93 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Fun struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type Args struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Args struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + X X `json:"X"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/002b_print_hello_10_times/002b_print_hello_10_times.go b/idioms/002b_print_hello_10_times/002b_print_hello_10_times.go new file mode 100644 index 0000000..66d19be --- /dev/null +++ b/idioms/002b_print_hello_10_times/002b_print_hello_10_times.go @@ -0,0 +1,10 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + fmt.Println(strings.Repeat("Hello\n", 10)) +} diff --git a/idioms/003a/003a.go b/idioms/003a/003a.go new file mode 100644 index 0000000..e6bce5a --- /dev/null +++ b/idioms/003a/003a.go @@ -0,0 +1,111 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Names struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type List struct { + Type string `json:"_type"` + Names []Names `json:"Names"` + Type0 Type0 `json:"Type"` +} +type Params struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Fun struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type X struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Y struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Args struct { + Type string `json:"_type"` + X X `json:"X"` + Op string `json:"Op"` + Y Y `json:"Y"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + X X `json:"X"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/003a_create_a_procedure/003a_create_a_procedure.go b/idioms/003a_create_a_procedure/003a_create_a_procedure.go new file mode 100644 index 0000000..fdfbae9 --- /dev/null +++ b/idioms/003a_create_a_procedure/003a_create_a_procedure.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func finish(name string) { + fmt.Println("My job here is done. Good bye " + name) +} + +func main() { + finish("Tony") +} diff --git a/idioms/003b/003b.go b/idioms/003b/003b.go new file mode 100644 index 0000000..1ce4080 --- /dev/null +++ b/idioms/003b/003b.go @@ -0,0 +1,91 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type RHS struct { + Type string `json:"_type"` + Type0 Type0 `json:"Type"` + Body Body `json:"Body"` +} +type Fun struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Args struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs,omitempty"` + Tok string `json:"Tok,omitempty"` + RHS []RHS `json:"Rhs,omitempty"` + X X `json:"X,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/003b_create_a_procedure/003b_create_a_procedure.go b/idioms/003b_create_a_procedure/003b_create_a_procedure.go new file mode 100644 index 0000000..a012afa --- /dev/null +++ b/idioms/003b_create_a_procedure/003b_create_a_procedure.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func main() { + + finish := func(name string) { + fmt.Println("My job here is done. Good bye " + name) + } + + finish("Tony") +} diff --git a/idioms/004/004.go b/idioms/004/004.go new file mode 100644 index 0000000..c4710e8 --- /dev/null +++ b/idioms/004/004.go @@ -0,0 +1,96 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Names struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type List struct { + Type string `json:"_type"` + Names []Names `json:"Names"` + Type0 Type0 `json:"Type"` +} +type Params struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Results struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results Results `json:"Results"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Y struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Results struct { + Type string `json:"_type"` + X X `json:"X"` + Op string `json:"Op"` + Y Y `json:"Y"` +} +type List struct { + Type string `json:"_type"` + Results []Results `json:"Results"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/004_create_a_function/004_create_a_function.go b/idioms/004_create_a_function/004_create_a_function.go new file mode 100644 index 0000000..024aa26 --- /dev/null +++ b/idioms/004_create_a_function/004_create_a_function.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func square(x int) int { + return x * x +} + +func main() { + n := square(9) + fmt.Println(n) +} diff --git a/idioms/005/005.go b/idioms/005/005.go new file mode 100644 index 0000000..dcb7bd9 --- /dev/null +++ b/idioms/005/005.go @@ -0,0 +1,104 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type RHS struct { + Type string `json:"_type"` + Type0 Type0 `json:"Type"` + Elts any `json:"Elts"` + Incomplete bool `json:"Incomplete"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Fun struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type Args struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs,omitempty"` + Tok string `json:"Tok,omitempty"` + RHS []RHS `json:"Rhs,omitempty"` + X X `json:"X,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/005_create_a_2d_point_data_structure/005_create_a_2d_point_data_structure.go b/idioms/005_create_a_2d_point_data_structure/005_create_a_2d_point_data_structure.go new file mode 100644 index 0000000..d0694c6 --- /dev/null +++ b/idioms/005_create_a_2d_point_data_structure/005_create_a_2d_point_data_structure.go @@ -0,0 +1,25 @@ +package main + +import "fmt" + +type Point struct { + x, y float64 +} + +func main() { + p1 := Point{} + p2 := Point{2.1, 2.2} + p3 := Point{ + y: 3.1, + x: 3.2, + } + p4 := &Point{ + x: 4.1, + y: 4.2, + } + + fmt.Println(p1) + fmt.Println(p2) + fmt.Println(p3) + fmt.Println(p4) +} diff --git a/idioms/006/006.go b/idioms/006/006.go new file mode 100644 index 0000000..ae210ee --- /dev/null +++ b/idioms/006/006.go @@ -0,0 +1,107 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Elt struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Len any `json:"Len"` + Elt Elt `json:"Elt"` +} +type Elts struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type RHS struct { + Type string `json:"_type"` + Type0 Type0 `json:"Type"` + Elts []Elts `json:"Elts"` + Incomplete bool `json:"Incomplete"` +} +type Key struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Value struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type List struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs,omitempty"` + Tok string `json:"Tok"` + RHS []RHS `json:"Rhs,omitempty"` + Key Key `json:"Key,omitempty"` + Value Value `json:"Value,omitempty"` + X X `json:"X,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/006_iterate_over_list_values/006_iterate_over_list_values.go b/idioms/006_iterate_over_list_values/006_iterate_over_list_values.go new file mode 100644 index 0000000..13a950f --- /dev/null +++ b/idioms/006_iterate_over_list_values/006_iterate_over_list_values.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []int{11, 22, 33} + + for _, x := range items { + doSomething(x) + } +} + +func doSomething(i int) { + fmt.Println(i) +} diff --git a/idioms/007/007.go b/idioms/007/007.go new file mode 100644 index 0000000..ae210ee --- /dev/null +++ b/idioms/007/007.go @@ -0,0 +1,107 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Elt struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Len any `json:"Len"` + Elt Elt `json:"Elt"` +} +type Elts struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type RHS struct { + Type string `json:"_type"` + Type0 Type0 `json:"Type"` + Elts []Elts `json:"Elts"` + Incomplete bool `json:"Incomplete"` +} +type Key struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Value struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type List struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs,omitempty"` + Tok string `json:"Tok"` + RHS []RHS `json:"Rhs,omitempty"` + Key Key `json:"Key,omitempty"` + Value Value `json:"Value,omitempty"` + X X `json:"X,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/007_iterate_over_list_indexes_and_values/007_iterate_over_list_indexes_and_values.go b/idioms/007_iterate_over_list_indexes_and_values/007_iterate_over_list_indexes_and_values.go new file mode 100644 index 0000000..3e2acd1 --- /dev/null +++ b/idioms/007_iterate_over_list_indexes_and_values/007_iterate_over_list_indexes_and_values.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + items := []string{ + "oranges", + "apples", + "bananas", + } + + for i, x := range items { + fmt.Printf("Item %d = %v \n", i, x) + } +} diff --git a/idioms/008/008.go b/idioms/008/008.go new file mode 100644 index 0000000..91a848b --- /dev/null +++ b/idioms/008/008.go @@ -0,0 +1,128 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Key struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Value struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Key Key `json:"Key"` + Value Value `json:"Value"` +} +type Key struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Value struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Elts struct { + Type string `json:"_type"` + Key Key `json:"Key"` + Value Value `json:"Value"` +} +type RHS struct { + Type string `json:"_type"` + Type0 Type0 `json:"Type"` + Elts []Elts `json:"Elts"` + Incomplete bool `json:"Incomplete"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Fun struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type Args struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs,omitempty"` + Tok string `json:"Tok,omitempty"` + RHS []RHS `json:"Rhs,omitempty"` + X X `json:"X,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/008_initialize_a_new_map_associative_array/008_initialize_a_new_map_associative_array.go b/idioms/008_initialize_a_new_map_associative_array/008_initialize_a_new_map_associative_array.go new file mode 100644 index 0000000..6c3b76b --- /dev/null +++ b/idioms/008_initialize_a_new_map_associative_array/008_initialize_a_new_map_associative_array.go @@ -0,0 +1,9 @@ +package main + +import "fmt" + +func main() { + x := map[string]int{"one": 1, "two": 2} + + fmt.Println(x) +} \ No newline at end of file diff --git a/idioms/009/009.go b/idioms/009/009.go new file mode 100644 index 0000000..298ed8f --- /dev/null +++ b/idioms/009/009.go @@ -0,0 +1,118 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Names struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + X X `json:"X"` +} +type List struct { + Type string `json:"_type"` + Names []Names `json:"Names"` + Type0 Type0 `json:"Type"` +} +type Params struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type Y struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Cond struct { + Type string `json:"_type"` + X X `json:"X"` + Op string `json:"Op"` + Y Y `json:"Y"` +} +type Fun struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Args struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type X struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + Init any `json:"Init,omitempty"` + Cond Cond `json:"Cond,omitempty"` + Body Body `json:"Body,omitempty"` + Else any `json:"Else,omitempty"` + X X `json:"X,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/009_create_a_binary_tree_data_structure/009_create_a_binary_tree_data_structure.go b/idioms/009_create_a_binary_tree_data_structure/009_create_a_binary_tree_data_structure.go new file mode 100644 index 0000000..bb6cc83 --- /dev/null +++ b/idioms/009_create_a_binary_tree_data_structure/009_create_a_binary_tree_data_structure.go @@ -0,0 +1,31 @@ +package main + +import "fmt" + +type BinTree struct { + Value int + Left *BinTree + Right *BinTree +} + +func inorder(root *BinTree) { + if root == nil { + return + } + + inorder(root.Left) + fmt.Printf("%d ", root.Value) + inorder(root.Right) +} + +func main() { + root := &BinTree{1, nil, nil} + root.Left = &BinTree{2, nil, nil} + root.Right = &BinTree{3, nil, nil} + root.Left.Left = &BinTree{4, nil, nil} + root.Left.Right = &BinTree{5, nil, nil} + root.Right.Right = &BinTree{6, nil, nil} + root.Left.Left.Left = &BinTree{7, nil, nil} + + inorder(root) +} diff --git a/idioms/010a/010a.go b/idioms/010a/010a.go new file mode 100644 index 0000000..bcaa07e --- /dev/null +++ b/idioms/010a/010a.go @@ -0,0 +1,122 @@ +package main + +type AutoGenerated struct { + Type string `json:"_type"` + Doc any `json:"Doc"` + Package any `json:"Package"` + Name Name `json:"Name"` + Decls []Decls `json:"Decls"` + Imports any `json:"Imports"` + Unresolved any `json:"Unresolved"` + Comments any `json:"Comments"` + FileSet FileSet `json:"FileSet"` +} +type Name struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Path struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type Specs struct { + Type string `json:"_type"` + Name any `json:"Name"` + Path Path `json:"Path"` +} +type Params struct { + Type string `json:"_type"` + List any `json:"List"` +} +type Type0 struct { + Type string `json:"_type"` + TypeParams any `json:"TypeParams"` + Params Params `json:"Params"` + Results any `json:"Results"` +} +type LHS struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Elt struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Type0 struct { + Type string `json:"_type"` + Len any `json:"Len"` + Elt Elt `json:"Elt"` +} +type Elts struct { + Type string `json:"_type"` + Kind string `json:"Kind"` + Value string `json:"Value"` +} +type RHS struct { + Type string `json:"_type"` + Type0 Type0 `json:"Type"` + Elts []Elts `json:"Elts"` + Incomplete bool `json:"Incomplete"` +} +type Key struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Sel struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type Fun struct { + Type string `json:"_type"` + X X `json:"X"` + Sel Sel `json:"Sel"` +} +type Args struct { + Type string `json:"_type"` + Name string `json:"Name"` +} +type X0 struct { + Type string `json:"_type"` + Fun Fun `json:"Fun"` + Args []Args `json:"Args"` +} +type List struct { + Type string `json:"_type"` + LHS []LHS `json:"Lhs,omitempty"` + Tok string `json:"Tok,omitempty"` + RHS []RHS `json:"Rhs,omitempty"` + Key Key `json:"Key,omitempty"` + Value any `json:"Value,omitempty"` + X X `json:"X,omitempty"` + Body Body `json:"Body,omitempty"` + X0 X0 `json:"X,omitempty"` +} +type Body struct { + Type string `json:"_type"` + List []List `json:"List"` +} +type Decls struct { + Type string `json:"_type"` + Tok string `json:"Tok,omitempty"` + Specs []Specs `json:"Specs,omitempty"` + Recv any `json:"Recv,omitempty"` + Name Name `json:"Name,omitempty"` + Type0 Type0 `json:"Type,omitempty"` + Body Body `json:"Body,omitempty"` +} +type Files struct { + Name string `json:"Name"` + Base int `json:"Base"` + Size int `json:"Size"` + Lines []int `json:"Lines"` + Infos any `json:"Infos"` +} +type FileSet struct { + Base int `json:"Base"` + Files []Files `json:"Files"` +} diff --git a/idioms/010a_shuffle_a_list/010a_shuffle_a_list.go b/idioms/010a_shuffle_a_list/010a_shuffle_a_list.go new file mode 100644 index 0000000..2dd0318 --- /dev/null +++ b/idioms/010a_shuffle_a_list/010a_shuffle_a_list.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + x := []string{"a", "b", "c", "d", "e", "f", "g", "h"} + + for i := range x { + j := rand.Intn(i + 1) + x[i], x[j] = x[j], x[i] + } + + fmt.Println(x) +} diff --git a/idioms/010b_shuffle_a_list/010b_shuffle_a_list.go b/idioms/010b_shuffle_a_list/010b_shuffle_a_list.go new file mode 100644 index 0000000..a917793 --- /dev/null +++ b/idioms/010b_shuffle_a_list/010b_shuffle_a_list.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + x := []string{"a", "b", "c", "d", "e", "f", "g", "h"} + + y := make([]string, len(x)) + perm := rand.Perm(len(x)) + for i, v := range perm { + y[v] = x[i] + } + + fmt.Println(y) +} diff --git a/idioms/010c_shuffle_a_list/010c_shuffle_a_list.go b/idioms/010c_shuffle_a_list/010c_shuffle_a_list.go new file mode 100644 index 0000000..2846556 --- /dev/null +++ b/idioms/010c_shuffle_a_list/010c_shuffle_a_list.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + x := []string{"a", "b", "c", "d", "e", "f", "g", "h"} + + rand.Shuffle(len(x), func(i, j int) { + x[i], x[j] = x[j], x[i] + }) + + fmt.Println(x) +} diff --git a/idioms/010d_shuffle_a_list/010d_shuffle_a_list.go b/idioms/010d_shuffle_a_list/010d_shuffle_a_list.go new file mode 100644 index 0000000..1f9ad91 --- /dev/null +++ b/idioms/010d_shuffle_a_list/010d_shuffle_a_list.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + x := []string{"a", "b", "c", "d", "e", "f", "g", "h"} + + for i := len(x) - 1; i > 0; i-- { + j := rand.Intn(i + 1) + x[i], x[j] = x[j], x[i] + } + + fmt.Println(x) +} \ No newline at end of file diff --git a/idioms/011a_pick_a_random_element_from_a_list/011a_pick_a_random_element_from_a_list.go b/idioms/011a_pick_a_random_element_from_a_list/011a_pick_a_random_element_from_a_list.go new file mode 100644 index 0000000..7a698cc --- /dev/null +++ b/idioms/011a_pick_a_random_element_from_a_list/011a_pick_a_random_element_from_a_list.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "math/rand" +) + +var x = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"} + +func main() { + fmt.Println(x[rand.Intn(len(x))]) +} diff --git a/idioms/012_check_if_list_contains_a_value/012_check_if_list_contains_a_value.go b/idioms/012_check_if_list_contains_a_value/012_check_if_list_contains_a_value.go new file mode 100644 index 0000000..00e0f61 --- /dev/null +++ b/idioms/012_check_if_list_contains_a_value/012_check_if_list_contains_a_value.go @@ -0,0 +1,20 @@ +package main + +import "fmt" + +func Contains(list []T, x T) bool { + for _, item := range list { + if item == x { + return true + } + } + return false +} + +type T string + +func main() { + list := []T{"a", "b", "c"} + fmt.Println(Contains(list, "b")) + fmt.Println(Contains(list, "z")) +} \ No newline at end of file diff --git a/idioms/013_iterate_over_map_keys_and_values/013_iterate_over_map_keys_and_values.go b/idioms/013_iterate_over_map_keys_and_values/013_iterate_over_map_keys_and_values.go new file mode 100644 index 0000000..a380730 --- /dev/null +++ b/idioms/013_iterate_over_map_keys_and_values/013_iterate_over_map_keys_and_values.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func main() { + mymap := map[string]int{ + "one": 1, + "two": 2, + "three": 3, + "four": 4, + } + + for k, x := range mymap { + fmt.Println("Key =", k, ", Value =", x) + } +} \ No newline at end of file diff --git a/idioms/014_pick_uniformly_a_random_floating_point_number_in_a_b/014_pick_uniformly_a_random_floating_point_number_in_a_b.go b/idioms/014_pick_uniformly_a_random_floating_point_number_in_a_b/014_pick_uniformly_a_random_floating_point_number_in_a_b.go new file mode 100644 index 0000000..07d6818 --- /dev/null +++ b/idioms/014_pick_uniformly_a_random_floating_point_number_in_a_b/014_pick_uniformly_a_random_floating_point_number_in_a_b.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + x := pick(-2.0, 6.5) + fmt.Println(x) +} + +func pick(a, b float64) float64 { + return a + (rand.Float64() * (b - a)) +} diff --git a/idioms/015_pick_uniformly_a_random_integer_in_a_b/015_pick_uniformly_a_random_integer_in_a_b.go b/idioms/015_pick_uniformly_a_random_integer_in_a_b/015_pick_uniformly_a_random_integer_in_a_b.go new file mode 100644 index 0000000..ce6e11d --- /dev/null +++ b/idioms/015_pick_uniformly_a_random_integer_in_a_b/015_pick_uniformly_a_random_integer_in_a_b.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + x := pick(3, 7) + + // Note that in the Go Playground, time and random don't change very often. + fmt.Println(x) +} + +func pick(a, b int) int { + return a + rand.Intn(b-a+1) +} diff --git a/idioms/016_depth_first_traversing_of_a_binary_tree/016_depth_first_traversing_of_a_binary_tree.go b/idioms/016_depth_first_traversing_of_a_binary_tree/016_depth_first_traversing_of_a_binary_tree.go new file mode 100644 index 0000000..ff82bf8 --- /dev/null +++ b/idioms/016_depth_first_traversing_of_a_binary_tree/016_depth_first_traversing_of_a_binary_tree.go @@ -0,0 +1,51 @@ +package main + +import . "fmt" + +type key string +type value string + +type BinTree struct { + Key key + Deco value + Left *BinTree + Right *BinTree +} + +func (bt *BinTree) Dfs(f func(*BinTree)) { + if bt == nil { + return + } + bt.Left.Dfs(f) + f(bt) + bt.Right.Dfs(f) +} + +func main() { + a := []key{"d", "a", "dd", "e", "h", "gg", "f", "b", "n", "v"} + tree := &BinTree{Key: a[0]} + for _, str := range a[1:] { + tree.Insert(str, value("")) + } + tree.Dfs(NodePrint) +} + +func (bt *BinTree) Insert(x key, v value) { + if x < bt.Key { + if bt.Left == nil { + bt.Left = &BinTree{Key: x, Deco: v} + } else { + bt.Left.Insert(x, v) + } + } else { + if bt.Right == nil { + bt.Right = &BinTree{Key: x, Deco: v} + } else { + bt.Right.Insert(x, v) + } + } +} + +func NodePrint(node *BinTree) { + Println(node.Key) +} diff --git a/idioms/017_create_a_tree_data_structure/017_create_a_tree_data_structure.go b/idioms/017_create_a_tree_data_structure/017_create_a_tree_data_structure.go new file mode 100644 index 0000000..a2cff19 --- /dev/null +++ b/idioms/017_create_a_tree_data_structure/017_create_a_tree_data_structure.go @@ -0,0 +1,42 @@ +package main + +import "fmt" + +type Tree struct { + Key key + Deco value + Children []*Tree +} + +type key string +type value string + +func (t *Tree) String() string { + str := "(" + str += string(t.Deco) + if len(t.Children) == 0 { + return str + ")" + } + str += " (" + for _, child := range t.Children { + str += child.String() + } + str += "))" + return str +} + +func (this *Tree) AddChild(x key, v value) *Tree { + child := &Tree{Key: x, Deco: v} + this.Children = append(this.Children, child) + return child +} + +func main() { + tree := &Tree{Key: "Granpa", Deco: "Abraham"} + subtree := tree.AddChild("Dad", "Homer") + subtree.AddChild("Kid 1", "Bart") + subtree.AddChild("Kid 2", "Lisa") + subtree.AddChild("Kid 3", "Maggie") + + fmt.Println(tree) +} diff --git a/idioms/018_depth_first_traversing_of_a_tree/018_depth_first_traversing_of_a_tree.go b/idioms/018_depth_first_traversing_of_a_tree/018_depth_first_traversing_of_a_tree.go new file mode 100644 index 0000000..281533b --- /dev/null +++ b/idioms/018_depth_first_traversing_of_a_tree/018_depth_first_traversing_of_a_tree.go @@ -0,0 +1,41 @@ +package main + +import . "fmt" + +func (t *Tree) Dfs(f func(*Tree)) { + if t == nil { + return + } + f(t) + for _, child := range t.Children { + child.Dfs(f) + } +} + +type key string +type value string + +type Tree struct { + Key key + Deco value + Children []*Tree +} + +func (this *Tree) AddChild(x key, v value) { + child := &Tree{Key: x, Deco: v} + this.Children = append(this.Children, child) +} + +func NodePrint(node *Tree) { + Printf("%v (%v)\n", node.Deco, node.Key) +} + +func main() { + tree := &Tree{Key: "Granpa", Deco: "Abraham"} + tree.AddChild("Dad", "Homer") + tree.Children[0].AddChild("Kid 1", "Bart") + tree.Children[0].AddChild("Kid 2", "Lisa") + tree.Children[0].AddChild("Kid 3", "Maggie") + + tree.Dfs(NodePrint) +} diff --git a/idioms/019_reverse_a_list/019_reverse_a_list.go b/idioms/019_reverse_a_list/019_reverse_a_list.go new file mode 100644 index 0000000..b8b9a98 --- /dev/null +++ b/idioms/019_reverse_a_list/019_reverse_a_list.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func main() { + + s := []int{5, 2, 6, 3, 1, 4} + + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } + + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/020_return_two_values/020_return_two_values.go b/idioms/020_return_two_values/020_return_two_values.go new file mode 100644 index 0000000..be65342 --- /dev/null +++ b/idioms/020_return_two_values/020_return_two_values.go @@ -0,0 +1,19 @@ +package main + +import "fmt" + +func main() { + matrix := [][]int{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + } + for x := 1; x <= 11; x += 2 { + found, i, j := search(matrix, x) + if found { + fmt.Printf("matrix[%v][%v] == %v \n", i, j, x) + } else { + fmt.Printf("Value %v not found. \n", x) + } + } +} diff --git a/idioms/021_swap_values/021_swap_values.go b/idioms/021_swap_values/021_swap_values.go new file mode 100644 index 0000000..2126d40 --- /dev/null +++ b/idioms/021_swap_values/021_swap_values.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func main() { + a := 3 + b := 10 + a, b = b, a + fmt.Println(a) + fmt.Println(b) +} diff --git a/idioms/022a_convert_string_to_integer/022a_convert_string_to_integer.go b/idioms/022a_convert_string_to_integer/022a_convert_string_to_integer.go new file mode 100644 index 0000000..3d1b04a --- /dev/null +++ b/idioms/022a_convert_string_to_integer/022a_convert_string_to_integer.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "reflect" + "strconv" +) + +func main() { + // create a string + s := "123" + fmt.Println(s) + fmt.Println("type:", reflect.TypeOf(s)) + + // convert string to int + i, err := strconv.Atoi(s) + if err != nil { + panic(err) + } + fmt.Println(i) + fmt.Println("type:", reflect.TypeOf(i)) +} diff --git a/idioms/022b_convert_string_to_integer/022b_convert_string_to_integer.go b/idioms/022b_convert_string_to_integer/022b_convert_string_to_integer.go new file mode 100644 index 0000000..99c76db --- /dev/null +++ b/idioms/022b_convert_string_to_integer/022b_convert_string_to_integer.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "reflect" + "strconv" +) + +func main() { + s := "123" + fmt.Println("s is", reflect.TypeOf(s), s) + + i, err := strconv.ParseInt(s, 10, 0) + if err != nil { + panic(err) + } + + fmt.Println("i is", reflect.TypeOf(i), i) +} diff --git a/idioms/023_convert_real_number_to_string_with_2_decimal_places/023_convert_real_number_to_string_with_2_decimal_places.go b/idioms/023_convert_real_number_to_string_with_2_decimal_places/023_convert_real_number_to_string_with_2_decimal_places.go new file mode 100644 index 0000000..ad77428 --- /dev/null +++ b/idioms/023_convert_real_number_to_string_with_2_decimal_places/023_convert_real_number_to_string_with_2_decimal_places.go @@ -0,0 +1,9 @@ +package main + +import "fmt" + +func main() { + x := 3.14159 + s := fmt.Sprintf("%.2f", x) + fmt.Println(s) +} diff --git "a/idioms/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263.go" "b/idioms/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263.go" new file mode 100644 index 0000000..17432f3 --- /dev/null +++ "b/idioms/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263/024_assign_to_string_the_japanese_word_\343\203\215\343\202\263.go" @@ -0,0 +1,8 @@ +package main + +import "fmt" + +func main() { + s := "ネコ" + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/025_send_a_value_to_another_thread/025_send_a_value_to_another_thread.go b/idioms/025_send_a_value_to_another_thread/025_send_a_value_to_another_thread.go new file mode 100644 index 0000000..c318bce --- /dev/null +++ b/idioms/025_send_a_value_to_another_thread/025_send_a_value_to_another_thread.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + ch := make(chan string) + + go func() { + v := <-ch + fmt.Printf("Hello, %v\n", v) + }() + + ch <- "Alan" + + // Make sure the non-main goroutine had the chance to finish. + time.Sleep(time.Second) +} diff --git a/idioms/026a_create_a_2_dimensional_array/026a_create_a_2_dimensional_array.go b/idioms/026a_create_a_2_dimensional_array/026a_create_a_2_dimensional_array.go new file mode 100644 index 0000000..224a4b4 --- /dev/null +++ b/idioms/026a_create_a_2_dimensional_array/026a_create_a_2_dimensional_array.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func main() { + const m, n = 3, 4 + var x [m][n]float64 + + x[1][2] = 8 + fmt.Println(x) +} diff --git a/idioms/026b_create_a_2_dimensional_array/026b_create_a_2_dimensional_array.go b/idioms/026b_create_a_2_dimensional_array/026b_create_a_2_dimensional_array.go new file mode 100644 index 0000000..c89af67 --- /dev/null +++ b/idioms/026b_create_a_2_dimensional_array/026b_create_a_2_dimensional_array.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main() { + x := make2D(2, 3) + + x[1][1] = 8 + fmt.Println(x) +} + +func make2D(m, n int) [][]float64 { + buf := make([]float64, m*n) + + x := make([][]float64, m) + for i := range x { + x[i] = buf[:n:n] + buf = buf[n:] + } + return x +} \ No newline at end of file diff --git a/idioms/027a_create_a_3_dimensional_array/027a_create_a_3_dimensional_array.go b/idioms/027a_create_a_3_dimensional_array/027a_create_a_3_dimensional_array.go new file mode 100644 index 0000000..74810ae --- /dev/null +++ b/idioms/027a_create_a_3_dimensional_array/027a_create_a_3_dimensional_array.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func main() { + const m, n, p = 2, 2, 3 + var x [m][n][p]float64 + + x[1][0][2] = 9 + + // Value of x + fmt.Println(x) + + // Type of x + fmt.Printf("%T", x) +} diff --git a/idioms/027b_create_a_3_dimensional_array/027b_create_a_3_dimensional_array.go b/idioms/027b_create_a_3_dimensional_array/027b_create_a_3_dimensional_array.go new file mode 100644 index 0000000..980d761 --- /dev/null +++ b/idioms/027b_create_a_3_dimensional_array/027b_create_a_3_dimensional_array.go @@ -0,0 +1,24 @@ +package main + +import "fmt" + +func main() { + x := make3D(2, 2, 3) + + x[1][0][2] = 9 + fmt.Println(x) +} + +func make3D(m, n, p int) [][][]float64 { + buf := make([]float64, m*n*p) + + x := make([][][]float64, m) + for i := range x { + x[i] = make([][]float64, n) + for j := range x[i] { + x[i][j] = buf[:p:p] + buf = buf[p:] + } + } + return x +} diff --git a/idioms/028a_sort_by_a_property/028a_sort_by_a_property.go b/idioms/028a_sort_by_a_property/028a_sort_by_a_property.go new file mode 100644 index 0000000..390cb95 --- /dev/null +++ b/idioms/028a_sort_by_a_property/028a_sort_by_a_property.go @@ -0,0 +1,34 @@ +package main + +import "fmt" +import "sort" + +type Item struct { + label string + p int + lang string +} + +type ItemPSorter []Item + +func (s ItemPSorter) Len() int { return len(s) } +func (s ItemPSorter) Less(i, j int) bool { return s[i].p < s[j].p } +func (s ItemPSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +func sortItems(items []Item) { + sorter := ItemPSorter(items) + sort.Sort(sorter) +} + +func main() { + items := []Item{ + {"twelve", 12, "english"}, + {"six", 6, "english"}, + {"eleven", 11, "english"}, + {"zero", 0, "english"}, + {"two", 2, "english"}, + } + fmt.Println("Unsorted: ", items) + sortItems(items) + fmt.Println("Sorted: ", items) +} diff --git a/idioms/028b_sort_by_a_property/028b_sort_by_a_property.go b/idioms/028b_sort_by_a_property/028b_sort_by_a_property.go new file mode 100644 index 0000000..eba758c --- /dev/null +++ b/idioms/028b_sort_by_a_property/028b_sort_by_a_property.go @@ -0,0 +1,28 @@ +package main + +import "fmt" +import "sort" + +type Item struct { + label string + p int + lang string +} + +func main() { + items := []Item{ + {"twelve", 12, "english"}, + {"six", 6, "english"}, + {"eleven", 11, "english"}, + {"zero", 0, "english"}, + {"two", 2, "english"}, + } + fmt.Println("Unsorted: ", items) + + less := func(i, j int) bool { + return items[i].p < items[j].p + } + sort.Slice(items, less) + + fmt.Println("Sorted: ", items) +} diff --git a/idioms/029_remove_item_from_list_by_its_index/029_remove_item_from_list_by_its_index.go b/idioms/029_remove_item_from_list_by_its_index/029_remove_item_from_list_by_its_index.go new file mode 100644 index 0000000..3e60c0d --- /dev/null +++ b/idioms/029_remove_item_from_list_by_its_index/029_remove_item_from_list_by_its_index.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []string{"a", "b", "c", "d", "e", "f"} + fmt.Println(items) + + i := 2 + items = append(items[:i], items[i+1:]...) + fmt.Println(items) +} \ No newline at end of file diff --git a/idioms/030_parallelize_execution_of_1000_independent_tasks/030_parallelize_execution_of_1000_independent_tasks.go b/idioms/030_parallelize_execution_of_1000_independent_tasks/030_parallelize_execution_of_1000_independent_tasks.go new file mode 100644 index 0000000..9d9ed25 --- /dev/null +++ b/idioms/030_parallelize_execution_of_1000_independent_tasks/030_parallelize_execution_of_1000_independent_tasks.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func f(i int) { + d := rand.Int() % 10000 + time.Sleep(time.Duration(d)) + fmt.Printf("Hello %v\n", i) +} + +func main() { + for i := 1; i <= 1000; i++ { + go f(i) + } + + time.Sleep(4 * time.Second) +} diff --git a/idioms/031_recursive_factorial_simple/031_recursive_factorial_simple.go b/idioms/031_recursive_factorial_simple/031_recursive_factorial_simple.go new file mode 100644 index 0000000..b0cc052 --- /dev/null +++ b/idioms/031_recursive_factorial_simple/031_recursive_factorial_simple.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +func f(i int) int { + if i == 0 { + return 1 + } + return i * f(i-1) +} + +func main() { + for i := 0; i <= 10; i++ { + fmt.Printf("f(%d) = %d\n", i, f(i)) + } +} \ No newline at end of file diff --git a/idioms/032_integer_exponentiation_by_squaring/032_integer_exponentiation_by_squaring.go b/idioms/032_integer_exponentiation_by_squaring/032_integer_exponentiation_by_squaring.go new file mode 100644 index 0000000..c82944f --- /dev/null +++ b/idioms/032_integer_exponentiation_by_squaring/032_integer_exponentiation_by_squaring.go @@ -0,0 +1,20 @@ +package main + +import "fmt" + +func exp(x, n int) int { + switch { + case n == 0: + return 1 + case n == 1: + return x + case n%2 == 0: + return exp(x*x, n/2) + default: + return x * exp(x*x, (n-1)/2) + } +} + +func main() { + fmt.Println(exp(3, 5)) +} \ No newline at end of file diff --git a/idioms/036_first_class_function_generic_composition/036_first_class_function_generic_composition.go b/idioms/036_first_class_function_generic_composition/036_first_class_function_generic_composition.go new file mode 100644 index 0000000..252ff01 --- /dev/null +++ b/idioms/036_first_class_function_generic_composition/036_first_class_function_generic_composition.go @@ -0,0 +1,23 @@ +package main + +import "fmt" + +func composeIntFuncs(f func(int) int, g func(int) int) func(int) int { + return func(x int) int { + return g(f(x)) + } +} + +func main() { + double := func(x int) int { + return 2 * x + } + addTwo := func(x int) int { + return x + 2 + } + h := composeIntFuncs(double, addTwo) + + for i := 0; i < 10; i++ { + fmt.Println(i, h(i), addTwo(double(i))) + } +} diff --git a/idioms/037_currying/037_currying.go b/idioms/037_currying/037_currying.go new file mode 100644 index 0000000..3d88f0d --- /dev/null +++ b/idioms/037_currying/037_currying.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "time" +) + +type Company string + +type Employee struct { + FirstName string + LastName string +} + +func (e *Employee) String() string { + return "<" + e.FirstName + " " + e.LastName + ">" +} + +type Payroll struct { + Company Company + Boss *Employee + Employee *Employee + StartDate time.Time + EndDate time.Time + Amount int +} + +// Creates a blank payroll for a specific employee with specific boss in specific company +type PayFactory func(Company, *Employee, *Employee) Payroll + +// Creates a blank payroll for a specific employee +type CustomPayFactory func(*Employee) Payroll + +func CurryPayFactory(pf PayFactory, company Company, boss *Employee) CustomPayFactory { + return func(e *Employee) Payroll { + return pf(company, boss, e) + } +} + +func NewPay(company Company, boss *Employee, employee *Employee) Payroll { + return Payroll{ + Company: company, + Boss: boss, + Employee: employee, + } +} + +func main() { + me := Employee{"Jack", "Power"} + + // I happen to be head of the HR department of Richissim Inc. + var myLittlePayFactory CustomPayFactory = CurryPayFactory(NewPay, "Richissim", &me) + + fmt.Println(myLittlePayFactory(&Employee{"Jean", "Dupont"})) + fmt.Println(myLittlePayFactory(&Employee{"Antoine", "Pol"})) +} diff --git a/idioms/039_check_if_string_contains_a_word/039_check_if_string_contains_a_word.go b/idioms/039_check_if_string_contains_a_word/039_check_if_string_contains_a_word.go new file mode 100644 index 0000000..2c2e03c --- /dev/null +++ b/idioms/039_check_if_string_contains_a_word/039_check_if_string_contains_a_word.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "Let's dance the macarena" + + word := "dance" + ok := strings.Contains(s, word) + fmt.Println(ok) + + word = "car" + ok = strings.Contains(s, word) + fmt.Println(ok) + + word = "duck" + ok = strings.Contains(s, word) + fmt.Println(ok) +} diff --git a/idioms/042_continue_outer_loop/042_continue_outer_loop.go b/idioms/042_continue_outer_loop/042_continue_outer_loop.go new file mode 100644 index 0000000..b6eb69f --- /dev/null +++ b/idioms/042_continue_outer_loop/042_continue_outer_loop.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func printSubtraction(a []int, b []int) { +mainloop: + for _, v := range a { + for _, w := range b { + if v == w { + continue mainloop + } + } + fmt.Println(v) + } +} + +func main() { + a := []int{1, 2, 3, 4} + b := []int{2, 4, 6, 8} + printSubtraction(a, b) +} diff --git a/idioms/043_break_outer_loop/043_break_outer_loop.go b/idioms/043_break_outer_loop/043_break_outer_loop.go new file mode 100644 index 0000000..fd7d2fa --- /dev/null +++ b/idioms/043_break_outer_loop/043_break_outer_loop.go @@ -0,0 +1,26 @@ +package main + +import "fmt" +import "os" + +var m = [][]int{ + {1, 2, 3}, + {11, 0, 30}, + {5, -20, 55}, + {0, 0, -60}, +} + +func main() { +mainloop: + for i, line := range m { + fmt.Fprintln(os.Stderr, "Searching in line", i) + for _, v := range line { + if v < 0 { + fmt.Println("Found ", v) + break mainloop + } + } + } + + fmt.Println("Done.") +} diff --git a/idioms/044_insert_element_in_list/044_insert_element_in_list.go b/idioms/044_insert_element_in_list/044_insert_element_in_list.go new file mode 100644 index 0000000..5184320 --- /dev/null +++ b/idioms/044_insert_element_in_list/044_insert_element_in_list.go @@ -0,0 +1,19 @@ +package main + +import "fmt" + +func main() { + + s := make([]int, 2) + + s[0] = 0 + s[1] = 2 + + fmt.Println(s) + // insert one at index one + s = append(s, 0) + copy(s[2:], s[1:]) + s[1] = 1 + + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/045_pause_execution_for_5_seconds/045_pause_execution_for_5_seconds.go b/idioms/045_pause_execution_for_5_seconds/045_pause_execution_for_5_seconds.go new file mode 100644 index 0000000..d97287c --- /dev/null +++ b/idioms/045_pause_execution_for_5_seconds/045_pause_execution_for_5_seconds.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + time.Sleep(5 * time.Second) + fmt.Println("Done.") +} diff --git a/idioms/048_multi_line_string_literal/048_multi_line_string_literal.go b/idioms/048_multi_line_string_literal/048_multi_line_string_literal.go new file mode 100644 index 0000000..256eae3 --- /dev/null +++ b/idioms/048_multi_line_string_literal/048_multi_line_string_literal.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" +) + +func main() { + s := `Huey +Dewey +Louie` + + fmt.Println(s) +} diff --git a/idioms/049a_split_a_space_separated_string/049a_split_a_space_separated_string.go b/idioms/049a_split_a_space_separated_string/049a_split_a_space_separated_string.go new file mode 100644 index 0000000..12b3ba0 --- /dev/null +++ b/idioms/049a_split_a_space_separated_string/049a_split_a_space_separated_string.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "Un dos tres" + chunks := strings.Split(s, " ") + fmt.Println(len(chunks)) + fmt.Println(chunks) + + s = " Un dos tres " + chunks = strings.Split(s, " ") + fmt.Println(len(chunks)) + fmt.Println(chunks) + + s = "Un dos" + chunks = strings.Split(s, " ") + fmt.Println(len(chunks)) + fmt.Println(chunks) +} \ No newline at end of file diff --git a/idioms/049b_split_a_space_separated_string/049b_split_a_space_separated_string.go b/idioms/049b_split_a_space_separated_string/049b_split_a_space_separated_string.go new file mode 100644 index 0000000..81d446c --- /dev/null +++ b/idioms/049b_split_a_space_separated_string/049b_split_a_space_separated_string.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "Un dos tres" + chunks := strings.Fields(s) + fmt.Println(len(chunks)) + fmt.Println(chunks) + + s = " Un dos tres " + chunks = strings.Fields(s) + fmt.Println(len(chunks)) + fmt.Println(chunks) + + s = "Un dos" + chunks = strings.Fields(s) + fmt.Println(len(chunks)) + fmt.Println(chunks) +} diff --git a/idioms/050_make_an_infinite_loop/050_make_an_infinite_loop.go b/idioms/050_make_an_infinite_loop/050_make_an_infinite_loop.go new file mode 100644 index 0000000..a1d8859 --- /dev/null +++ b/idioms/050_make_an_infinite_loop/050_make_an_infinite_loop.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func main() { + k := 0 + for { + fmt.Println("Hello, playground") + k++ + if k == 5 { + break + } + } +} \ No newline at end of file diff --git a/idioms/051_check_if_map_contains_key/051_check_if_map_contains_key.go b/idioms/051_check_if_map_contains_key/051_check_if_map_contains_key.go new file mode 100644 index 0000000..e288629 --- /dev/null +++ b/idioms/051_check_if_map_contains_key/051_check_if_map_contains_key.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" +) + +func main() { + m := map[string]int{ + "uno": 1, + "dos": 2, + "tres": 3, + } + + k := "cinco" + _, ok := m[k] + fmt.Printf("m contains key %q: %v\n", k, ok) + + k = "tres" + _, ok = m[k] + fmt.Printf("m contains key %q: %v\n", k, ok) +} diff --git a/idioms/053_join_a_list_of_strings/053_join_a_list_of_strings.go b/idioms/053_join_a_list_of_strings/053_join_a_list_of_strings.go new file mode 100644 index 0000000..ae64041 --- /dev/null +++ b/idioms/053_join_a_list_of_strings/053_join_a_list_of_strings.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + x := []string{"eggs", "butter", "milk"} + + y := strings.Join(x, ", ") + + fmt.Printf("%q", y) +} diff --git a/idioms/054_compute_sum_of_integers/054_compute_sum_of_integers.go b/idioms/054_compute_sum_of_integers/054_compute_sum_of_integers.go new file mode 100644 index 0000000..61c9e56 --- /dev/null +++ b/idioms/054_compute_sum_of_integers/054_compute_sum_of_integers.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func main() { + x := []int{1, 2, 3} + s := 0 + for _, v := range x { + s += v + } + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/055a_convert_integer_to_string/055a_convert_integer_to_string.go b/idioms/055a_convert_integer_to_string/055a_convert_integer_to_string.go new file mode 100644 index 0000000..6f53643 --- /dev/null +++ b/idioms/055a_convert_integer_to_string/055a_convert_integer_to_string.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "strconv" +) + +func main() { + var i int = 1234 + s := strconv.Itoa(i) + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/055b_convert_integer_to_string/055b_convert_integer_to_string.go b/idioms/055b_convert_integer_to_string/055b_convert_integer_to_string.go new file mode 100644 index 0000000..62ae23a --- /dev/null +++ b/idioms/055b_convert_integer_to_string/055b_convert_integer_to_string.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "strconv" +) + +func main() { + var i int64 = 1234 + s := strconv.FormatInt(i, 10) + fmt.Println(s) +} diff --git a/idioms/055c_convert_integer_to_string/055c_convert_integer_to_string.go b/idioms/055c_convert_integer_to_string/055c_convert_integer_to_string.go new file mode 100644 index 0000000..56ab716 --- /dev/null +++ b/idioms/055c_convert_integer_to_string/055c_convert_integer_to_string.go @@ -0,0 +1,18 @@ +package main + +import "fmt" +import "math/big" + +func main() { + var i int = 1234 + s := fmt.Sprintf("%d", i) + fmt.Println(s) + + var j int = 5678 + s = fmt.Sprintf("%d", j) + fmt.Println(s) + + var k *big.Int = big.NewInt(90123456) + s = fmt.Sprintf("%d", k) + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/056_launch_1000_parallel_tasks_and_wait_for_completion/056_launch_1000_parallel_tasks_and_wait_for_completion.go b/idioms/056_launch_1000_parallel_tasks_and_wait_for_completion/056_launch_1000_parallel_tasks_and_wait_for_completion.go new file mode 100644 index 0000000..3d4fd39 --- /dev/null +++ b/idioms/056_launch_1000_parallel_tasks_and_wait_for_completion/056_launch_1000_parallel_tasks_and_wait_for_completion.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" +) + +func f(i int) { + d := rand.Int() % 10000 + time.Sleep(time.Duration(d)) + fmt.Printf("Hello %v\n", i) +} + +func main() { + var wg sync.WaitGroup + wg.Add(1000) + for i := 1; i <= 1000; i++ { + go func(i int) { + f(i) + wg.Done() + }(i) + } + wg.Wait() + fmt.Println("Finished") +} \ No newline at end of file diff --git a/idioms/058_extract_file_content_to_a_string/058_extract_file_content_to_a_string.go b/idioms/058_extract_file_content_to_a_string/058_extract_file_content_to_a_string.go new file mode 100644 index 0000000..aa5d287 --- /dev/null +++ b/idioms/058_extract_file_content_to_a_string/058_extract_file_content_to_a_string.go @@ -0,0 +1,25 @@ +package main + +import "fmt" +import "io/ioutil" + +func main() { + f := "data.txt" + b, err := ioutil.ReadFile(f) + if err != nil { + panic(err) + } + lines := string(b) + + fmt.Println(lines) +} + +// Create file in fake FS of the Playground. init is executed before main. +func init() { + err := ioutil.WriteFile("data.txt", []byte(`Un +Dos +Tres`), 0644) + if err != nil { + panic(err) + } +} diff --git a/idioms/059_write_to_standard_error_stream/059_write_to_standard_error_stream.go b/idioms/059_write_to_standard_error_stream/059_write_to_standard_error_stream.go new file mode 100644 index 0000000..fe6cd82 --- /dev/null +++ b/idioms/059_write_to_standard_error_stream/059_write_to_standard_error_stream.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + x := -2 + fmt.Fprintln(os.Stderr, x, "is negative") +} diff --git a/idioms/061_get_current_date/061_get_current_date.go b/idioms/061_get_current_date/061_get_current_date.go new file mode 100644 index 0000000..595f0e9 --- /dev/null +++ b/idioms/061_get_current_date/061_get_current_date.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + d := time.Now() + fmt.Println("Now is", d) + // The Playground has a special sandbox, so you may get a Time value fixed in the past. +} \ No newline at end of file diff --git a/idioms/062_find_substring_position/062_find_substring_position.go b/idioms/062_find_substring_position/062_find_substring_position.go new file mode 100644 index 0000000..69eb91d --- /dev/null +++ b/idioms/062_find_substring_position/062_find_substring_position.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + x := "été chaud" + + { + y := "chaud" + i := strings.Index(x, y) + fmt.Println(i) + } + + { + y := "froid" + i := strings.Index(x, y) + fmt.Println(i) + } +} diff --git a/idioms/063_replace_fragment_of_a_string/063_replace_fragment_of_a_string.go b/idioms/063_replace_fragment_of_a_string/063_replace_fragment_of_a_string.go new file mode 100644 index 0000000..5338eea --- /dev/null +++ b/idioms/063_replace_fragment_of_a_string/063_replace_fragment_of_a_string.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + x := "oink oink oink" + y := "oink" + z := "moo" + x2 := strings.Replace(x, y, z, -1) + fmt.Println(x2) +} diff --git a/idioms/065_format_decimal_number/065_format_decimal_number.go b/idioms/065_format_decimal_number/065_format_decimal_number.go new file mode 100644 index 0000000..fe66cac --- /dev/null +++ b/idioms/065_format_decimal_number/065_format_decimal_number.go @@ -0,0 +1,9 @@ +package main + +import "fmt" + +func main() { + x := 0.15625 + s := fmt.Sprintf("%.1f%%", 100.0*x) + fmt.Println(s) +} diff --git a/idioms/066_big_integer_exponentiation/066_big_integer_exponentiation.go b/idioms/066_big_integer_exponentiation/066_big_integer_exponentiation.go new file mode 100644 index 0000000..bd11ca7 --- /dev/null +++ b/idioms/066_big_integer_exponentiation/066_big_integer_exponentiation.go @@ -0,0 +1,18 @@ +package main + +import "fmt" +import "math/big" + +func exp(x *big.Int, n int) *big.Int { + nb := big.NewInt(int64(n)) + var z big.Int + z.Exp(x, nb, nil) + return &z +} + +func main() { + x := big.NewInt(3) + n := 5 + z := exp(x, n) + fmt.Println(z) +} diff --git a/idioms/068b_create_a_bitset/068b_create_a_bitset.go b/idioms/068b_create_a_bitset/068b_create_a_bitset.go new file mode 100644 index 0000000..4d4cef2 --- /dev/null +++ b/idioms/068b_create_a_bitset/068b_create_a_bitset.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" +) + +const n = 1024 + +func main() { + x := make([]bool, n) + + x[42] = true + + for _, y := range []int{13, 42} { + fmt.Println("x has bit", y, "set to", x[y]) + } +} \ No newline at end of file diff --git a/idioms/068c_create_a_bitset/068c_create_a_bitset.go b/idioms/068c_create_a_bitset/068c_create_a_bitset.go new file mode 100644 index 0000000..73b7649 --- /dev/null +++ b/idioms/068c_create_a_bitset/068c_create_a_bitset.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" +) + +func main() { + const n = 1024 + + x := NewBitset(n) + + x.SetBit(13) + x.SetBit(42) + x.ClearBit(13) + + for _, y := range []int{13, 42} { + fmt.Println("x has bit", y, "set to", x.GetBit(y)) + } +} + +type Bitset []uint64 + +func NewBitset(n int) Bitset { + return make(Bitset, (n+63)/64) +} + +func (b Bitset) GetBit(index int) bool { + pos := index / 64 + j := index % 64 + return (b[pos] & (uint64(1) << j)) != 0 +} + +func (b Bitset) SetBit(index int) { + pos := index / 64 + j := index % 64 + b[pos] |= (uint64(1) << j) +} + +func (b Bitset) ClearBit(index int) { + pos := index / 64 + j := index % 64 + b[pos] ^= (uint64(1) << j) +} diff --git a/idioms/069a_seed_random_generator/069a_seed_random_generator.go b/idioms/069a_seed_random_generator/069a_seed_random_generator.go new file mode 100644 index 0000000..bab6c55 --- /dev/null +++ b/idioms/069a_seed_random_generator/069a_seed_random_generator.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + var s int64 = 42 + rand.Seed(s) + fmt.Println(rand.Int()) +} diff --git a/idioms/069b_seed_random_generator/069b_seed_random_generator.go b/idioms/069b_seed_random_generator/069b_seed_random_generator.go new file mode 100644 index 0000000..f999d9c --- /dev/null +++ b/idioms/069b_seed_random_generator/069b_seed_random_generator.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + var s int64 = 42 + r := rand.New(rand.NewSource(s)) + fmt.Println(r.Int()) +} diff --git a/idioms/070a_use_clock_as_random_generator_seed/070a_use_clock_as_random_generator_seed.go b/idioms/070a_use_clock_as_random_generator_seed/070a_use_clock_as_random_generator_seed.go new file mode 100644 index 0000000..2ff11dd --- /dev/null +++ b/idioms/070a_use_clock_as_random_generator_seed/070a_use_clock_as_random_generator_seed.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + rand.Seed(time.Now().UnixNano()) + // Well, the playground date is actually fixed in the past, and the + // output is cached. + // But if you run this on your workstation, the output will vary. + fmt.Println(rand.Intn(999)) +} \ No newline at end of file diff --git a/idioms/070b_use_clock_as_random_generator_seed/070b_use_clock_as_random_generator_seed.go b/idioms/070b_use_clock_as_random_generator_seed/070b_use_clock_as_random_generator_seed.go new file mode 100644 index 0000000..79f78e6 --- /dev/null +++ b/idioms/070b_use_clock_as_random_generator_seed/070b_use_clock_as_random_generator_seed.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + // Well, the playground date is actually fixed in the past, and the + // output is cached. + // But if you run this on your workstation, the output will vary. + fmt.Println(r.Intn(999)) +} diff --git a/idioms/071_echo_program_implementation/071_echo_program_implementation.go b/idioms/071_echo_program_implementation/071_echo_program_implementation.go new file mode 100644 index 0000000..2ae88ed --- /dev/null +++ b/idioms/071_echo_program_implementation/071_echo_program_implementation.go @@ -0,0 +1,9 @@ +package main + +import "fmt" +import "os" +import "strings" + +func main() { + fmt.Println(strings.Join(os.Args[1:], " ")) +} \ No newline at end of file diff --git a/idioms/073_create_a_factory/073_create_a_factory.go b/idioms/073_create_a_factory/073_create_a_factory.go new file mode 100644 index 0000000..dcd14e9 --- /dev/null +++ b/idioms/073_create_a_factory/073_create_a_factory.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +type Parent struct { + name string +} + +// A Factory is a function which returns an object +type ParentFactory func(string) Parent + +func main() { + var fact ParentFactory = func(str string) Parent { + return Parent{ + name: str, + } + } + + var p Parent = fact("Daddy") + fmt.Println(p) +} diff --git a/idioms/076a_binary_digits_from_an_integer/076a_binary_digits_from_an_integer.go b/idioms/076a_binary_digits_from_an_integer/076a_binary_digits_from_an_integer.go new file mode 100644 index 0000000..828280a --- /dev/null +++ b/idioms/076a_binary_digits_from_an_integer/076a_binary_digits_from_an_integer.go @@ -0,0 +1,11 @@ +package main + +import "fmt" +import "strconv" + +func main() { + x := int64(13) + s := strconv.FormatInt(x, 2) + + fmt.Println(s) +} diff --git a/idioms/076b_binary_digits_from_an_integer/076b_binary_digits_from_an_integer.go b/idioms/076b_binary_digits_from_an_integer/076b_binary_digits_from_an_integer.go new file mode 100644 index 0000000..80c3097 --- /dev/null +++ b/idioms/076b_binary_digits_from_an_integer/076b_binary_digits_from_an_integer.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + x := big.NewInt(13) + s := fmt.Sprintf("%b", x) + + fmt.Println(s) +} \ No newline at end of file diff --git a/idioms/078a_do_while_loop/078a_do_while_loop.go b/idioms/078a_do_while_loop/078a_do_while_loop.go new file mode 100644 index 0000000..9faf239 --- /dev/null +++ b/idioms/078a_do_while_loop/078a_do_while_loop.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + for { + x := rollDice() + fmt.Println("Got", x) + if x == 3 { + break + } + + } +} + +func rollDice() int { + return 1 + rand.Intn(6) +} diff --git a/idioms/078b_do_while_loop/078b_do_while_loop.go b/idioms/078b_do_while_loop/078b_do_while_loop.go new file mode 100644 index 0000000..8baf23f --- /dev/null +++ b/idioms/078b_do_while_loop/078b_do_while_loop.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + for done := false; !done; { + x := rollDice() + fmt.Println("Got", x) + done = x == 3 + } +} + +func rollDice() int { + return 1 + rand.Intn(6) +} diff --git a/idioms/079_convert_integer_to_floating_point_number/079_convert_integer_to_floating_point_number.go b/idioms/079_convert_integer_to_floating_point_number/079_convert_integer_to_floating_point_number.go new file mode 100644 index 0000000..5dc1cbf --- /dev/null +++ b/idioms/079_convert_integer_to_floating_point_number/079_convert_integer_to_floating_point_number.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "reflect" +) + +func main() { + x := 5 + y := float64(x) + + fmt.Println(y) + fmt.Printf("%.2f\n", y) + fmt.Println(reflect.TypeOf(y)) +} diff --git a/idioms/080_truncate_floating_point_number_to_integer/080_truncate_floating_point_number_to_integer.go b/idioms/080_truncate_floating_point_number_to_integer/080_truncate_floating_point_number_to_integer.go new file mode 100644 index 0000000..a35e700 --- /dev/null +++ b/idioms/080_truncate_floating_point_number_to_integer/080_truncate_floating_point_number_to_integer.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func main() { + a := -6.4 + b := 6.4 + c := 6.6 + fmt.Println(int(a)) + fmt.Println(int(b)) + fmt.Println(int(c)) +} \ No newline at end of file diff --git a/idioms/081_round_floating_point_number_to_integer/081_round_floating_point_number_to_integer.go b/idioms/081_round_floating_point_number_to_integer/081_round_floating_point_number_to_integer.go new file mode 100644 index 0000000..36f1bdd --- /dev/null +++ b/idioms/081_round_floating_point_number_to_integer/081_round_floating_point_number_to_integer.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "math" +) + +func round(x float64) int { + y := int(math.Floor(x + 0.5)) + return y +} + +func main() { + for _, x := range []float64{-1.1, -0.9, -0.5, -0.1, 0., 0.1, 0.5, 0.9, 1.1} { + fmt.Printf("%5.1f %5d\n", x, round(x)) + } +} diff --git a/idioms/082_count_substring_occurrences/082_count_substring_occurrences.go b/idioms/082_count_substring_occurrences/082_count_substring_occurrences.go new file mode 100644 index 0000000..2235cfe --- /dev/null +++ b/idioms/082_count_substring_occurrences/082_count_substring_occurrences.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "Romaromamam" + t := "mam" + + x := strings.Count(s, t) + + fmt.Println(x) +} diff --git a/idioms/083_regex_with_character_repetition/083_regex_with_character_repetition.go b/idioms/083_regex_with_character_repetition/083_regex_with_character_repetition.go new file mode 100644 index 0000000..a9ec737 --- /dev/null +++ b/idioms/083_regex_with_character_repetition/083_regex_with_character_repetition.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "regexp" +) + +func main() { + r := regexp.MustCompile("htt+p") + + for _, s := range []string{ + "hp", + "htp", + "http", + "htttp", + "httttp", + "htttttp", + "htttttp", + "word htttp in a sentence", + } { + fmt.Println(s, "=>", r.MatchString(s)) + } +} diff --git a/idioms/084a_count_bits_set_in_integer_binary_representation/084a_count_bits_set_in_integer_binary_representation.go b/idioms/084a_count_bits_set_in_integer_binary_representation/084a_count_bits_set_in_integer_binary_representation.go new file mode 100644 index 0000000..e5a6785 --- /dev/null +++ b/idioms/084a_count_bits_set_in_integer_binary_representation/084a_count_bits_set_in_integer_binary_representation.go @@ -0,0 +1,37 @@ +package main + +import "fmt" + +func PopCountUInt64(i uint64) (c int) { + // bit population count, see + // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel + i -= (i >> 1) & 0x5555555555555555 + i = (i>>2)&0x3333333333333333 + i&0x3333333333333333 + i += i >> 4 + i &= 0x0f0f0f0f0f0f0f0f + i *= 0x0101010101010101 + return int(i >> 56) +} + +func PopCountUInt32(i uint32) (n int) { + // bit population count, see + // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel + i -= (i >> 1) & 0x55555555 + i = (i>>2)&0x33333333 + i&0x33333333 + i += i >> 4 + i &= 0x0f0f0f0f + i *= 0x01010101 + return int(i >> 24) +} + +func main() { + for i := uint64(0); i < 16; i++ { + c := PopCountUInt64(i) + fmt.Printf("%4d %04[1]b %d\n", i, c) + } + + for i := uint32(0); i < 16; i++ { + c := PopCountUInt32(i) + fmt.Printf("%4d %04[1]b %d\n", i, c) + } +} diff --git a/idioms/084b_count_bits_set_in_integer_binary_representation/084b_count_bits_set_in_integer_binary_representation.go b/idioms/084b_count_bits_set_in_integer_binary_representation/084b_count_bits_set_in_integer_binary_representation.go new file mode 100644 index 0000000..59627ef --- /dev/null +++ b/idioms/084b_count_bits_set_in_integer_binary_representation/084b_count_bits_set_in_integer_binary_representation.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + "math/bits" +) + +func main() { + for i := uint(0); i < 16; i++ { + c := bits.OnesCount(i) + fmt.Printf("%4d %04[1]b %d\n", i, c) + } +} diff --git a/idioms/085_check_if_integer_addition_will_overflow/085_check_if_integer_addition_will_overflow.go b/idioms/085_check_if_integer_addition_will_overflow/085_check_if_integer_addition_will_overflow.go new file mode 100644 index 0000000..6b58bf0 --- /dev/null +++ b/idioms/085_check_if_integer_addition_will_overflow/085_check_if_integer_addition_will_overflow.go @@ -0,0 +1,24 @@ +// You can edit this code! +// Click here and start typing. +package main + +import ( + "fmt" + "math" +) + +func addingWillOverflow(x int, y int) bool { + if x > 0 { + return y > math.MaxInt-x + } + return y < math.MinInt-x +} + +func main() { + fmt.Println(addingWillOverflow(math.MaxInt, math.MaxInt)) + fmt.Println(addingWillOverflow(math.MaxInt, math.MinInt)) + fmt.Println(addingWillOverflow(math.MinInt, math.MinInt)) + fmt.Println(addingWillOverflow(0, 0)) + fmt.Println(addingWillOverflow(0, math.MaxInt)) + fmt.Println(addingWillOverflow(0, math.MinInt)) +} diff --git a/idioms/087_stop_program/087_stop_program.go b/idioms/087_stop_program/087_stop_program.go new file mode 100644 index 0000000..d7d714f --- /dev/null +++ b/idioms/087_stop_program/087_stop_program.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + fmt.Println("Program starts") + os.Exit(0) + fmt.Println("Statement not reached") +} diff --git a/idioms/088_allocate_1m_bytes/088_allocate_1m_bytes.go b/idioms/088_allocate_1m_bytes/088_allocate_1m_bytes.go new file mode 100644 index 0000000..c242650 --- /dev/null +++ b/idioms/088_allocate_1m_bytes/088_allocate_1m_bytes.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func main() { + buf := make([]byte, 1000000) + + for i, b := range buf { + if b != 0 { + fmt.Println("Found unexpected value", b, "at position", i) + } + } + fmt.Println("Buffer was correctly initialized with zero values.") +} \ No newline at end of file diff --git a/idioms/089_handle_invalid_argument/089_handle_invalid_argument.go b/idioms/089_handle_invalid_argument/089_handle_invalid_argument.go new file mode 100644 index 0000000..53e802f --- /dev/null +++ b/idioms/089_handle_invalid_argument/089_handle_invalid_argument.go @@ -0,0 +1,33 @@ +package main + +import "fmt" + +// NewSquareMatrix creates a N-by-N matrix +func NewSquareMatrix(N int) ([][]float64, error) { + if N < 0 { + return nil, fmt.Errorf("Invalid size %d: order cannot be negative", N) + } + matrix := make([][]float64, N) + for i := range matrix { + matrix[i] = make([]float64, N) + } + return matrix, nil +} + +func main() { + N1 := 3 + matrix1, err1 := NewSquareMatrix(N1) + if err1 == nil { + fmt.Println(matrix1) + } else { + fmt.Println(err1) + } + + N2 := -2 + matrix2, err2 := NewSquareMatrix(N2) + if err2 == nil { + fmt.Println(matrix2) + } else { + fmt.Println(err2) + } +} diff --git a/idioms/091a_load_json_file_into_object/091a_load_json_file_into_object.go b/idioms/091a_load_json_file_into_object/091a_load_json_file_into_object.go new file mode 100644 index 0000000..937b888 --- /dev/null +++ b/idioms/091a_load_json_file_into_object/091a_load_json_file_into_object.go @@ -0,0 +1,46 @@ +package main + +import "fmt" +import "io/ioutil" +import "encoding/json" + +func readJSONFile() error { + var x Person + + buffer, err := ioutil.ReadFile(filename) + if err != nil { + return err + } + err = json.Unmarshal(buffer, &x) + if err != nil { + return err + } + + fmt.Println(x) + return nil +} + +func main() { + err := readJSONFile() + if err != nil { + panic(err) + } +} + +type Person struct { + FirstName string + Age int +} + +const filename = "/tmp/data.json" + +func init() { + err := ioutil.WriteFile(filename, []byte(` + { + "FirstName":"Napoléon", + "Age": 51 + }`), 0644) + if err != nil { + panic(err) + } +} diff --git a/idioms/091b_load_json_file_into_object/091b_load_json_file_into_object.go b/idioms/091b_load_json_file_into_object/091b_load_json_file_into_object.go new file mode 100644 index 0000000..df7464c --- /dev/null +++ b/idioms/091b_load_json_file_into_object/091b_load_json_file_into_object.go @@ -0,0 +1,50 @@ +package main + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" +) + +func readJSONFile() error { + var x Person + + r, err := os.Open(filename) + if err != nil { + return err + } + decoder := json.NewDecoder(r) + err = decoder.Decode(&x) + if err != nil { + return err + } + + fmt.Println(x) + return nil +} + +func main() { + err := readJSONFile() + if err != nil { + panic(err) + } +} + +type Person struct { + FirstName string + Age int +} + +const filename = "/tmp/data.json" + +func init() { + err := ioutil.WriteFile(filename, []byte(` + { + "FirstName":"Napoléon", + "Age": 51 + }`), 0644) + if err != nil { + panic(err) + } +} diff --git a/idioms/092_save_object_into_json_file/092_save_object_into_json_file.go b/idioms/092_save_object_into_json_file/092_save_object_into_json_file.go new file mode 100644 index 0000000..f3956d8 --- /dev/null +++ b/idioms/092_save_object_into_json_file/092_save_object_into_json_file.go @@ -0,0 +1,33 @@ +package main + +import "fmt" +import "io/ioutil" +import "encoding/json" + +func writeJSONFile() error { + x := Person{ + FirstName: "Napoléon", + Age: 51, + } + + buffer, err := json.MarshalIndent(x, "", " ") + if err != nil { + return err + } + return ioutil.WriteFile(filename, buffer, 0644) +} + +func main() { + err := writeJSONFile() + if err != nil { + panic(err) + } + fmt.Println("Done.") +} + +type Person struct { + FirstName string + Age int +} + +const filename = "/tmp/data.json" diff --git a/idioms/093_pass_a_runnable_procedure_as_parameter/093_pass_a_runnable_procedure_as_parameter.go b/idioms/093_pass_a_runnable_procedure_as_parameter/093_pass_a_runnable_procedure_as_parameter.go new file mode 100644 index 0000000..b64db48 --- /dev/null +++ b/idioms/093_pass_a_runnable_procedure_as_parameter/093_pass_a_runnable_procedure_as_parameter.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func main() { + control(greet) +} + +func control(f func()) { + fmt.Println("Before f") + f() + fmt.Println("After f") +} + +func greet() { + fmt.Println("Hello, developers") +} diff --git a/idioms/094a_print_type_of_variable/094a_print_type_of_variable.go b/idioms/094a_print_type_of_variable/094a_print_type_of_variable.go new file mode 100644 index 0000000..2622da1 --- /dev/null +++ b/idioms/094a_print_type_of_variable/094a_print_type_of_variable.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "os" + "reflect" +) + +func main() { + var x interface{} + + x = "Hello" + fmt.Println(reflect.TypeOf(x)) + + x = 4 + fmt.Println(reflect.TypeOf(x)) + + x = os.NewFile(0777, "foobar.txt") + fmt.Println(reflect.TypeOf(x)) +} diff --git a/idioms/094b_print_type_of_variable/094b_print_type_of_variable.go b/idioms/094b_print_type_of_variable/094b_print_type_of_variable.go new file mode 100644 index 0000000..bd5c230 --- /dev/null +++ b/idioms/094b_print_type_of_variable/094b_print_type_of_variable.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + var x interface{} + + x = "Hello" + fmt.Printf("%T", x) + fmt.Println() + + x = 4 + fmt.Printf("%T", x) + fmt.Println() + + x = os.NewFile(0777, "foobar.txt") + fmt.Printf("%T", x) + fmt.Println() +} diff --git a/idioms/095_get_file_size/095_get_file_size.go b/idioms/095_get_file_size/095_get_file_size.go new file mode 100644 index 0000000..18876be --- /dev/null +++ b/idioms/095_get_file_size/095_get_file_size.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" +) + +func main() { + err := printSize("file.txt") + if err != nil { + panic(err) + } +} + +func printSize(path string) error { + info, err := os.Stat(path) + if err != nil { + return err + } + x := info.Size() + + fmt.Println(x) + return nil +} + +func init() { + // The file will only contains the characters "Hello", no newlines. + buffer := []byte("Hello") + err := ioutil.WriteFile("file.txt", buffer, 0644) + if err != nil { + panic(err) + } +} diff --git a/idioms/098_epoch_seconds_to_date_object/098_epoch_seconds_to_date_object.go b/idioms/098_epoch_seconds_to_date_object/098_epoch_seconds_to_date_object.go new file mode 100644 index 0000000..b91543d --- /dev/null +++ b/idioms/098_epoch_seconds_to_date_object/098_epoch_seconds_to_date_object.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + ts := int64(1451606400) + d := time.Unix(ts, 0) + + fmt.Println(d) +} diff --git a/idioms/099_format_date_yyyy_mm_dd/099_format_date_yyyy_mm_dd.go b/idioms/099_format_date_yyyy_mm_dd/099_format_date_yyyy_mm_dd.go new file mode 100644 index 0000000..c229a6f --- /dev/null +++ b/idioms/099_format_date_yyyy_mm_dd/099_format_date_yyyy_mm_dd.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + d := time.Now() + x := d.Format("2006-01-02") + fmt.Println(x) + + // The output may be "2009-11-10" because the Playground's clock is fixed in the past. +} \ No newline at end of file diff --git a/idioms/100a_sort_by_a_comparator/100a_sort_by_a_comparator.go b/idioms/100a_sort_by_a_comparator/100a_sort_by_a_comparator.go new file mode 100644 index 0000000..9af8516 --- /dev/null +++ b/idioms/100a_sort_by_a_comparator/100a_sort_by_a_comparator.go @@ -0,0 +1,39 @@ +package main + +import "fmt" +import "sort" + +type Item struct { + label string + p int + lang string +} + +// c returns true if x is "inferior to" y (in a custom way) +func c(x, y Item) bool { + return x.p < y.p +} + +type ItemCSorter []Item + +func (s ItemCSorter) Len() int { return len(s) } +func (s ItemCSorter) Less(i, j int) bool { return c(s[i], s[j]) } +func (s ItemCSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } + +func sortItems(items []Item) { + sorter := ItemCSorter(items) + sort.Sort(sorter) +} + +func main() { + items := []Item{ + {"twelve", 12, "english"}, + {"six", 6, "english"}, + {"eleven", 11, "english"}, + {"zero", 0, "english"}, + {"two", 2, "english"}, + } + fmt.Println("Unsorted: ", items) + sortItems(items) + fmt.Println("Sorted: ", items) +} diff --git a/idioms/100b_sort_by_a_comparator/100b_sort_by_a_comparator.go b/idioms/100b_sort_by_a_comparator/100b_sort_by_a_comparator.go new file mode 100644 index 0000000..9ed21f1 --- /dev/null +++ b/idioms/100b_sort_by_a_comparator/100b_sort_by_a_comparator.go @@ -0,0 +1,45 @@ +package main + +import "fmt" +import "sort" + +type Item struct { + label string + p int + lang string +} + +type ItemsSorter struct { + items []Item + c func(x, y Item) bool +} + +func (s ItemsSorter) Len() int { return len(s.items) } +func (s ItemsSorter) Less(i, j int) bool { return s.c(s.items[i], s.items[j]) } +func (s ItemsSorter) Swap(i, j int) { s.items[i], s.items[j] = s.items[j], s.items[i] } + +func sortItems(items []Item, c func(x, y Item) bool) { + sorter := ItemsSorter{ + items, + c, + } + sort.Sort(sorter) +} + +func main() { + items := []Item{ + {"twelve", 12, "english"}, + {"six", 6, "english"}, + {"eleven", 11, "english"}, + {"zero", 0, "english"}, + {"two", 2, "english"}, + } + fmt.Println("Unsorted: ", items) + + c := func(x, y Item) bool { + return x.p < y.p + } + sortItems(items, c) + + fmt.Println("Sorted: ", items) +} diff --git a/idioms/100c_sort_by_a_comparator/100c_sort_by_a_comparator.go b/idioms/100c_sort_by_a_comparator/100c_sort_by_a_comparator.go new file mode 100644 index 0000000..05c0d23 --- /dev/null +++ b/idioms/100c_sort_by_a_comparator/100c_sort_by_a_comparator.go @@ -0,0 +1,32 @@ +package main + +import "fmt" +import "sort" + +type Item struct { + label string + p int + lang string +} + +// c returns true if x is "inferior to" y (in a custom way) +func c(x, y Item) bool { + return x.p < y.p +} + +func main() { + items := []Item{ + {"twelve", 12, "english"}, + {"six", 6, "english"}, + {"eleven", 11, "english"}, + {"zero", 0, "english"}, + {"two", 2, "english"}, + } + fmt.Println("Unsorted: ", items) + + sort.Slice(items, func(i, j int) bool { + return c(items[i], items[j]) + }) + + fmt.Println("Sorted: ", items) +} diff --git a/idioms/101_load_from_http_get_request_into_a_string/101_load_from_http_get_request_into_a_string.go b/idioms/101_load_from_http_get_request_into_a_string/101_load_from_http_get_request_into_a_string.go new file mode 100644 index 0000000..3d3745e --- /dev/null +++ b/idioms/101_load_from_http_get_request_into_a_string/101_load_from_http_get_request_into_a_string.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "io/ioutil" + "net" + "net/http" +) + +func main() { + u := "http://" + localhost + "/hello?name=Inigo+Montoya" + + res, err := http.Get(u) + check(err) + buffer, err := ioutil.ReadAll(res.Body) + res.Body.Close() + check(err) + s := string(buffer) + + fmt.Println("GET response:", res.StatusCode, s) +} + +const localhost = "127.0.0.1:3000" + +func init() { + http.HandleFunc("/hello", myHandler) + startServer() +} + +func myHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Hello %s", r.FormValue("name")) +} + +func startServer() { + listener, err := net.Listen("tcp", localhost) + check(err) + + go http.Serve(listener, nil) +} + +func check(err error) { + if err != nil { + panic(err) + } +} \ No newline at end of file diff --git a/idioms/102_load_from_http_get_request_into_a_file/102_load_from_http_get_request_into_a_file.go b/idioms/102_load_from_http_get_request_into_a_file/102_load_from_http_get_request_into_a_file.go new file mode 100644 index 0000000..16e3058 --- /dev/null +++ b/idioms/102_load_from_http_get_request_into_a_file/102_load_from_http_get_request_into_a_file.go @@ -0,0 +1,79 @@ +package main + +import ( + "fmt" + "io" + "io/ioutil" + "net" + "net/http" + "os" +) + +func main() { + err := saveGetResponse() + check(err) + err = readFile() + check(err) + + fmt.Println("Done.") +} + +func saveGetResponse() error { + u := "http://" + localhost + "/hello?name=Inigo+Montoya" + + fmt.Println("Making GET request") + resp, err := http.Get(u) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return fmt.Errorf("Status: %v", resp.Status) + } + + fmt.Println("Saving data to file") + out, err := os.Create("/tmp/result.txt") + if err != nil { + return err + } + defer out.Close() + _, err = io.Copy(out, resp.Body) + if err != nil { + return err + } + return nil +} + +func readFile() error { + fmt.Println("Reading file") + buffer, err := ioutil.ReadFile("/tmp/result.txt") + if err != nil { + return err + } + fmt.Printf("Saved data is %q\n", string(buffer)) + return nil +} + +const localhost = "127.0.0.1:3000" + +func init() { + http.HandleFunc("/hello", myHandler) + startServer() +} + +func myHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Hello %s", r.FormValue("name")) +} + +func startServer() { + listener, err := net.Listen("tcp", localhost) + check(err) + + go http.Serve(listener, nil) +} + +func check(err error) { + if err != nil { + panic(err) + } +} diff --git a/idioms/103_load_xml_file_into_struct/103_load_xml_file_into_struct.go b/idioms/103_load_xml_file_into_struct/103_load_xml_file_into_struct.go new file mode 100644 index 0000000..273b4ed --- /dev/null +++ b/idioms/103_load_xml_file_into_struct/103_load_xml_file_into_struct.go @@ -0,0 +1,49 @@ +package main + +import ( + "encoding/xml" + "fmt" +) +import "io/ioutil" + +func readXMLFile() error { + var x Person + + buffer, err := ioutil.ReadFile(filename) + if err != nil { + return err + } + err = xml.Unmarshal(buffer, &x) + if err != nil { + return err + } + + fmt.Println(x) + return nil +} + +func main() { + err := readXMLFile() + if err != nil { + panic(err) + } +} + +type Person struct { + FirstName string + Age int +} + +const filename = "/tmp/data.xml" + +func init() { + data := ` + + Napoléon + 51 + ` + err := ioutil.WriteFile(filename, []byte(data), 0644) + if err != nil { + panic(err) + } +} diff --git a/idioms/104_save_object_into_xml_file/104_save_object_into_xml_file.go b/idioms/104_save_object_into_xml_file/104_save_object_into_xml_file.go new file mode 100644 index 0000000..aa9d7da --- /dev/null +++ b/idioms/104_save_object_into_xml_file/104_save_object_into_xml_file.go @@ -0,0 +1,41 @@ +package main + +import "encoding/xml" +import "io/ioutil" +import "fmt" + +func writeXMLFile() error { + x := Person{ + FirstName: "Napoléon", + Age: 51, + } + + buffer, err := xml.MarshalIndent(x, "", " ") + if err != nil { + return err + } + return ioutil.WriteFile(filename, buffer, 0644) +} + +func main() { + err := writeXMLFile() + if err != nil { + panic(err) + } + fmt.Println("Done.") + + readBackBuffer, err := ioutil.ReadFile(filename) + if err != nil { + panic(err) + } + readBack := string(readBackBuffer) + fmt.Println("File", filename, "now contains:") + fmt.Println(readBack) +} + +type Person struct { + FirstName string + Age int +} + +const filename = "/tmp/data.xml" diff --git a/idioms/105_current_executable_name/105_current_executable_name.go b/idioms/105_current_executable_name/105_current_executable_name.go new file mode 100644 index 0000000..71db9a4 --- /dev/null +++ b/idioms/105_current_executable_name/105_current_executable_name.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" +) + +func main() { + var s string + + path := os.Args[0] + s = filepath.Base(path) + + fmt.Println(s) +} diff --git a/idioms/106_get_program_working_directory/106_get_program_working_directory.go b/idioms/106_get_program_working_directory/106_get_program_working_directory.go new file mode 100644 index 0000000..97561d3 --- /dev/null +++ b/idioms/106_get_program_working_directory/106_get_program_working_directory.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + dir, err := os.Getwd() + fmt.Println(dir, err) +} diff --git a/idioms/107_get_folder_containing_current_program/107_get_folder_containing_current_program.go b/idioms/107_get_folder_containing_current_program/107_get_folder_containing_current_program.go new file mode 100644 index 0000000..bdad5f9 --- /dev/null +++ b/idioms/107_get_folder_containing_current_program/107_get_folder_containing_current_program.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" +) + +func main() { + var dir string + + programPath := os.Args[0] + absolutePath, err := filepath.Abs(programPath) + if err != nil { + panic(err) + } + dir = filepath.Dir(absolutePath) + + fmt.Println(dir) +} diff --git a/idioms/110_check_if_string_is_blank/110_check_if_string_is_blank.go b/idioms/110_check_if_string_is_blank/110_check_if_string_is_blank.go new file mode 100644 index 0000000..a1286b4 --- /dev/null +++ b/idioms/110_check_if_string_is_blank/110_check_if_string_is_blank.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + for _, s := range []string{ + "", + "a", + " ", + "\t \n", + "_", + } { + blank := strings.TrimSpace(s) == "" + + if blank { + fmt.Printf("%q is blank\n", s) + } else { + fmt.Printf("%q is not blank\n", s) + } + } +} diff --git a/idioms/111_launch_other_program/111_launch_other_program.go b/idioms/111_launch_other_program/111_launch_other_program.go new file mode 100644 index 0000000..b84e5d1 --- /dev/null +++ b/idioms/111_launch_other_program/111_launch_other_program.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" + "os/exec" +) + +func main() { + err := exec.Command("x", "a", "b").Run() + fmt.Println(err) +} diff --git a/idioms/112_iterate_over_map_entries_ordered_by_keys/112_iterate_over_map_entries_ordered_by_keys.go b/idioms/112_iterate_over_map_entries_ordered_by_keys/112_iterate_over_map_entries_ordered_by_keys.go new file mode 100644 index 0000000..e544ad6 --- /dev/null +++ b/idioms/112_iterate_over_map_entries_ordered_by_keys/112_iterate_over_map_entries_ordered_by_keys.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "sort" +) + +func main() { + mymap := map[string]int{ + "one": 1, + "two": 2, + "three": 3, + "four": 4, + } + + keys := make([]string, 0, len(mymap)) + for k := range mymap { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + x := mymap[k] + fmt.Println("Key =", k, ", Value =", x) + } +} diff --git a/idioms/113a_iterate_over_map_entries_ordered_by_values/113a_iterate_over_map_entries_ordered_by_values.go b/idioms/113a_iterate_over_map_entries_ordered_by_values/113a_iterate_over_map_entries_ordered_by_values.go new file mode 100644 index 0000000..e359918 --- /dev/null +++ b/idioms/113a_iterate_over_map_entries_ordered_by_values/113a_iterate_over_map_entries_ordered_by_values.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "sort" +) + +type entry struct { + key string + value int +} +type entries []entry + +func (list entries) Len() int { return len(list) } +func (list entries) Less(i, j int) bool { return list[i].value < list[j].value } +func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] } + +func main() { + mymap := map[string]int{ + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "dos": 2, + "deux": 2, + } + + entries := make(entries, 0, len(mymap)) + for k, x := range mymap { + entries = append(entries, entry{key: k, value: x}) + } + sort.Sort(entries) + + for _, e := range entries { + fmt.Println("Key =", e.key, ", Value =", e.value) + } +} diff --git a/idioms/113b_iterate_over_map_entries_ordered_by_values/113b_iterate_over_map_entries_ordered_by_values.go b/idioms/113b_iterate_over_map_entries_ordered_by_values/113b_iterate_over_map_entries_ordered_by_values.go new file mode 100644 index 0000000..35cd997 --- /dev/null +++ b/idioms/113b_iterate_over_map_entries_ordered_by_values/113b_iterate_over_map_entries_ordered_by_values.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "sort" +) + +func main() { + mymap := map[string]int{ + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "dos": 2, + "deux": 2, + } + + type entry struct { + key string + value int + } + + entries := make([]entry, 0, len(mymap)) + for k, x := range mymap { + entries = append(entries, entry{key: k, value: x}) + } + sort.Slice(entries, func(i, j int) bool { + return entries[i].value < entries[j].value + }) + + for _, e := range entries { + fmt.Println("Key =", e.key, ", Value =", e.value) + } +} diff --git a/idioms/115_compare_dates/115_compare_dates.go b/idioms/115_compare_dates/115_compare_dates.go new file mode 100644 index 0000000..b38ba89 --- /dev/null +++ b/idioms/115_compare_dates/115_compare_dates.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + d1 := time.Now() + d2 := time.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC) + + b := d1.Before(d2) + + fmt.Println(b) +} diff --git a/idioms/116a_remove_occurrences_of_word_from_string/116a_remove_occurrences_of_word_from_string.go b/idioms/116a_remove_occurrences_of_word_from_string/116a_remove_occurrences_of_word_from_string.go new file mode 100644 index 0000000..849d000 --- /dev/null +++ b/idioms/116a_remove_occurrences_of_word_from_string/116a_remove_occurrences_of_word_from_string.go @@ -0,0 +1,13 @@ +package main + +import "fmt" +import "strings" + +func main() { + s1 := "foobarfoo" + w := "foo" + + s2 := strings.Replace(s1, w, "", -1) + + fmt.Println(s2) +} \ No newline at end of file diff --git a/idioms/116b_remove_occurrences_of_word_from_string/116b_remove_occurrences_of_word_from_string.go b/idioms/116b_remove_occurrences_of_word_from_string/116b_remove_occurrences_of_word_from_string.go new file mode 100644 index 0000000..bf9060f --- /dev/null +++ b/idioms/116b_remove_occurrences_of_word_from_string/116b_remove_occurrences_of_word_from_string.go @@ -0,0 +1,13 @@ +package main + +import "fmt" +import "strings" + +func main() { + s1 := "foobarfoo" + w := "foo" + + s2 := strings.ReplaceAll(s1, w, "") + + fmt.Println(s2) +} \ No newline at end of file diff --git a/idioms/117_get_list_size/117_get_list_size.go b/idioms/117_get_list_size/117_get_list_size.go new file mode 100644 index 0000000..b71aefa --- /dev/null +++ b/idioms/117_get_list_size/117_get_list_size.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + // x is a slice + x := []string{"a", "b", "c"} + n := len(x) + fmt.Println(n) + + // y is an array + y := [4]string{"a", "b", "c"} + n = len(y) + fmt.Println(n) +} diff --git a/idioms/118_list_to_set/118_list_to_set.go b/idioms/118_list_to_set/118_list_to_set.go new file mode 100644 index 0000000..024cf75 --- /dev/null +++ b/idioms/118_list_to_set/118_list_to_set.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + x := []string{"b", "a", "b", "c"} + fmt.Println("x =", x) + + y := make(map[string]struct{}, len(x)) + for _, v := range x { + y[v] = struct{}{} + } + + fmt.Println("y =", y) +} diff --git a/idioms/119a_deduplicate_list/119a_deduplicate_list.go b/idioms/119a_deduplicate_list/119a_deduplicate_list.go new file mode 100644 index 0000000..dd6a213 --- /dev/null +++ b/idioms/119a_deduplicate_list/119a_deduplicate_list.go @@ -0,0 +1,24 @@ +package main + +import "fmt" + +func main() { + type T string + x := []T{"b", "a", "b", "c"} + fmt.Println("x =", x) + + y := make(map[T]struct{}, len(x)) + for _, v := range x { + y[v] = struct{}{} + } + x2 := make([]T, 0, len(y)) + for _, v := range x { + if _, ok := y[v]; ok { + x2 = append(x2, v) + delete(y, v) + } + } + x = x2 + + fmt.Println("x =", x) +} diff --git a/idioms/119b_deduplicate_list/119b_deduplicate_list.go b/idioms/119b_deduplicate_list/119b_deduplicate_list.go new file mode 100644 index 0000000..ff8053d --- /dev/null +++ b/idioms/119b_deduplicate_list/119b_deduplicate_list.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func main() { + type T string + x := []T{"b", "a", "b", "b", "c", "b", "a"} + fmt.Println("x =", x) + + seen := make(map[T]bool) + j := 0 + for _, v := range x { + if !seen[v] { + x[j] = v + j++ + seen[v] = true + } + } + x = x[:j] + + fmt.Println("x =", x) +} diff --git a/idioms/120a_read_integer_from_stdin/120a_read_integer_from_stdin.go b/idioms/120a_read_integer_from_stdin/120a_read_integer_from_stdin.go new file mode 100644 index 0000000..0b9311c --- /dev/null +++ b/idioms/120a_read_integer_from_stdin/120a_read_integer_from_stdin.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" +) + +// This string simulates the keyboard entry. +var userInput string = `42 017` + +func main() { + var i int + _, err := fmt.Scan(&i) + fmt.Println(i, err) + + // The second value starts with 0, thus is interpreted as octal! + var j int + _, err = fmt.Scan(&j) + fmt.Println(j, err) +} + +// The Go Playground doesn't actually read os.Stdin, so this +// workaround writes some data on virtual FS in a file, and then +// sets this file as the new Stdin. +// +// Note that the init func is run before main. +func init() { + err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644) + if err != nil { + panic(err) + } + fileIn, err := os.Open("/tmp/stdin") + if err != nil { + panic(err) + } + os.Stdin = fileIn +} diff --git a/idioms/120b_read_integer_from_stdin/120b_read_integer_from_stdin.go b/idioms/120b_read_integer_from_stdin/120b_read_integer_from_stdin.go new file mode 100644 index 0000000..2e70638 --- /dev/null +++ b/idioms/120b_read_integer_from_stdin/120b_read_integer_from_stdin.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" +) + +// This string simulates the keyboard entry. +var userInput string = `42 017` + +func main() { + var i int + _, err := fmt.Scanf("%d", &i) + fmt.Println(i, err) + + var j int + _, err = fmt.Scanf("%d", &j) + fmt.Println(j, err) +} + +// The Go Playground doesn't actually read os.Stdin, so this +// workaround writes some data on virtual FS in a file, and then +// sets this file as the new Stdin. +// +// Note that the init func is run before main. +func init() { + err := ioutil.WriteFile("/tmp/stdin", []byte(userInput), 0644) + if err != nil { + panic(err) + } + fileIn, err := os.Open("/tmp/stdin") + if err != nil { + panic(err) + } + os.Stdin = fileIn +} diff --git a/idioms/122_declare_enumeration/122_declare_enumeration.go b/idioms/122_declare_enumeration/122_declare_enumeration.go new file mode 100644 index 0000000..dd834c1 --- /dev/null +++ b/idioms/122_declare_enumeration/122_declare_enumeration.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +type Suit int + +const ( + Spades Suit = iota + Hearts + Diamonds + Clubs +) + +func main() { + fmt.Printf("Hearts has type %T and value %d", Hearts, Hearts) +} diff --git a/idioms/123_assert_condition/123_assert_condition.go b/idioms/123_assert_condition/123_assert_condition.go new file mode 100644 index 0000000..a377ccd --- /dev/null +++ b/idioms/123_assert_condition/123_assert_condition.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +// +// The code may look fine, but +// obviously we have a bug. +// + +func main() { + salary = 65000 + employees = 120000 + totalPayroll = salary * employees + + if !isConsistent() { + panic("State consistency violated") + } + fmt.Println("Everything fine") +} + +var salary int32 +var employees int32 +var totalPayroll int32 + +func isConsistent() bool { + return salary >= 0 && + employees >= 0 && + totalPayroll >= 0 +} diff --git a/idioms/124b_binary_search_for_a_value_in_sorted_array/124b_binary_search_for_a_value_in_sorted_array.go b/idioms/124b_binary_search_for_a_value_in_sorted_array/124b_binary_search_for_a_value_in_sorted_array.go new file mode 100644 index 0000000..cefe873 --- /dev/null +++ b/idioms/124b_binary_search_for_a_value_in_sorted_array/124b_binary_search_for_a_value_in_sorted_array.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "sort" +) + +func binarySearch(a []int, x int) int { + i := sort.SearchInts(a, x) + if i < len(a) && a[i] == x { + return i + } + return -1 +} + +func main() { + a := []int{-2, -1, 0, 1, 1, 1, 6, 8, 8, 9, 10} + for x := -5; x <= 15; x++ { + i := binarySearch(a, x) + if i == -1 { + fmt.Println("Value", x, "not found") + } else { + fmt.Println("Value", x, "found at index", i) + } + } +} diff --git a/idioms/125a_measure_function_call_duration/125a_measure_function_call_duration.go b/idioms/125a_measure_function_call_duration/125a_measure_function_call_duration.go new file mode 100644 index 0000000..71dbd29 --- /dev/null +++ b/idioms/125a_measure_function_call_duration/125a_measure_function_call_duration.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + t1 := time.Now() + foo() + t := time.Since(t1) + ns := int64(t / time.Nanosecond) + + // Note that the clock is fixed in the Playground, so the resulting duration is always zero + fmt.Printf("%dns\n", ns) +} + +func foo() { + fmt.Println("Hello") +} diff --git a/idioms/125b_measure_function_call_duration/125b_measure_function_call_duration.go b/idioms/125b_measure_function_call_duration/125b_measure_function_call_duration.go new file mode 100644 index 0000000..a287eab --- /dev/null +++ b/idioms/125b_measure_function_call_duration/125b_measure_function_call_duration.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + t1 := time.Now() + foo() + t := time.Since(t1) + ns := t.Nanoseconds() + fmt.Printf("%dns\n", ns) +} + +func foo() { + fmt.Println("Hello") +} diff --git a/idioms/126_multiple_return_values/126_multiple_return_values.go b/idioms/126_multiple_return_values/126_multiple_return_values.go new file mode 100644 index 0000000..bd522a3 --- /dev/null +++ b/idioms/126_multiple_return_values/126_multiple_return_values.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + s, b := foo() + fmt.Println(s, b) +} + +func foo() (string, bool) { + return "Too good to be", true +} diff --git a/idioms/128_breadth_first_traversing_of_a_tree/128_breadth_first_traversing_of_a_tree.go b/idioms/128_breadth_first_traversing_of_a_tree/128_breadth_first_traversing_of_a_tree.go new file mode 100644 index 0000000..bc6ae42 --- /dev/null +++ b/idioms/128_breadth_first_traversing_of_a_tree/128_breadth_first_traversing_of_a_tree.go @@ -0,0 +1,47 @@ +package main + +import "fmt" + +func (root *Tree) Bfs(f func(*Tree)) { + if root == nil { + return + } + queue := []*Tree{root} + for len(queue) > 0 { + t := queue[0] + queue = queue[1:] + f(t) + queue = append(queue, t.Children...) + } +} + +type key string +type value string + +type Tree struct { + Key key + Deco value + Children []*Tree +} + +func (this *Tree) AddChild(x key, v value) { + child := &Tree{Key: x, Deco: v} + this.Children = append(this.Children, child) +} + +func NodePrint(node *Tree) { + fmt.Printf("%v (%v)\n", node.Key, node.Deco) +} + +func main() { + tree := &Tree{Key: "World", Deco: "Our planet"} + tree.AddChild("Europe", "A continent") + tree.Children[0].AddChild("Germany", "A country") + tree.Children[0].AddChild("Ireland", "A country") + tree.Children[0].AddChild("Mediterranean Sea", "A sea") + tree.AddChild("Asia", "A continent") + tree.Children[0].AddChild("Japan", "A country") + tree.Children[0].AddChild("Thailand", "A country") + + tree.Bfs(NodePrint) +} diff --git a/idioms/131_successive_conditions/131_successive_conditions.go b/idioms/131_successive_conditions/131_successive_conditions.go new file mode 100644 index 0000000..527310f --- /dev/null +++ b/idioms/131_successive_conditions/131_successive_conditions.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + "strings" +) + +func conditional(x string) { + switch { + case c1(x): + f1() + case c2(x): + f2() + case c3(x): + f3() + } +} + +func main() { + conditional("dog Snoopy") + conditional("fruit Raspberry") +} + +func f1() { + fmt.Println("I'm a Human") +} + +func f2() { + fmt.Println("I'm a Dog") +} + +func f3() { + fmt.Println("I'm a Fruit") +} + +var c1, c2, c3 = prefixCheck("human"), prefixCheck("dog"), prefixCheck("fruit") + +func prefixCheck(prefix string) func(string) bool { + return func(x string) bool { + return strings.HasPrefix(x, prefix) + } +} diff --git a/idioms/132_measure_duration_of_procedure_execution/132_measure_duration_of_procedure_execution.go b/idioms/132_measure_duration_of_procedure_execution/132_measure_duration_of_procedure_execution.go new file mode 100644 index 0000000..57c4828 --- /dev/null +++ b/idioms/132_measure_duration_of_procedure_execution/132_measure_duration_of_procedure_execution.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "regexp" + "strings" + "time" +) + +func clock(f func()) time.Duration { + t := time.Now() + f() + return time.Since(t) +} + +func f() { + re := regexp.MustCompilePOSIX("|A+{300}") + re.FindAllString(strings.Repeat("A", 299), -1) +} + +func main() { + d := clock(f) + + // The result is always zero in the playground, which has a fixed clock! + // Try it on your workstation instead. + fmt.Println(d) +} diff --git a/idioms/133_case_insensitive_string_contains/133_case_insensitive_string_contains.go b/idioms/133_case_insensitive_string_contains/133_case_insensitive_string_contains.go new file mode 100644 index 0000000..6b17f47 --- /dev/null +++ b/idioms/133_case_insensitive_string_contains/133_case_insensitive_string_contains.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "strings" +) + +// Package _strings has no case-insensitive version of _Contains, so +// we have to make our own. +func containsCaseInsensitive(s, word string) bool { + lowerS, lowerWord := strings.ToLower(s), strings.ToLower(word) + ok := strings.Contains(lowerS, lowerWord) + return ok +} + +func main() { + s := "Let's dance the macarena" + + word := "Dance" + ok := containsCaseInsensitive(s, word) + fmt.Println(ok) + + word = "dance" + ok = containsCaseInsensitive(s, word) + fmt.Println(ok) + + word = "Duck" + ok = containsCaseInsensitive(s, word) + fmt.Println(ok) +} diff --git a/idioms/135_remove_item_from_list_by_its_value/135_remove_item_from_list_by_its_value.go b/idioms/135_remove_item_from_list_by_its_value/135_remove_item_from_list_by_its_value.go new file mode 100644 index 0000000..13572c7 --- /dev/null +++ b/idioms/135_remove_item_from_list_by_its_value/135_remove_item_from_list_by_its_value.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []string{"a", "b", "c", "d", "e", "f"} + fmt.Println(items) + + x := "c" + for i, y := range items { + if y == x { + items = append(items[:i], items[i+1:]...) + break + } + } + fmt.Println(items) +} \ No newline at end of file diff --git a/idioms/137a_check_if_string_contains_only_digits/137a_check_if_string_contains_only_digits.go b/idioms/137a_check_if_string_contains_only_digits/137a_check_if_string_contains_only_digits.go new file mode 100644 index 0000000..fb650aa --- /dev/null +++ b/idioms/137a_check_if_string_contains_only_digits/137a_check_if_string_contains_only_digits.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" +) + +func main() { + for _, s := range []string{ + "123", + "", + "abc123def", + "abc", + "123.456", + "123 456", + } { + b := true + for _, c := range s { + if c < '0' || c > '9' { + b = false + break + } + } + fmt.Println(s, "=>", b) + } +} \ No newline at end of file diff --git a/idioms/137b_check_if_string_contains_only_digits/137b_check_if_string_contains_only_digits.go b/idioms/137b_check_if_string_contains_only_digits/137b_check_if_string_contains_only_digits.go new file mode 100644 index 0000000..10a6c5c --- /dev/null +++ b/idioms/137b_check_if_string_contains_only_digits/137b_check_if_string_contains_only_digits.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + for _, s := range []string{ + "123", + "", + "abc123def", + "abc", + "123.456", + "123 456", + } { + isNotDigit := func(c rune) bool { return c < '0' || c > '9' } + b := strings.IndexFunc(s, isNotDigit) == -1 + fmt.Println(s, "=>", b) + } +} \ No newline at end of file diff --git a/idioms/138_create_temp_file/138_create_temp_file.go b/idioms/138_create_temp_file/138_create_temp_file.go new file mode 100644 index 0000000..1c3f510 --- /dev/null +++ b/idioms/138_create_temp_file/138_create_temp_file.go @@ -0,0 +1,36 @@ +package main + +import ( + "io/ioutil" + "log" + "os" +) + +func main() { + content := []byte("Big bag of misc data") + + log.Println("Opening new temp file") + tmpfile, err := ioutil.TempFile("", "example") + if err != nil { + log.Fatal(err) + } + tmpfilename := tmpfile.Name() + defer os.Remove(tmpfilename) // clean up + log.Println("Opened new file", tmpfilename) + + log.Println("Writing [[", string(content), "]]") + if _, err := tmpfile.Write(content); err != nil { + log.Fatal(err) + } + if err := tmpfile.Close(); err != nil { + log.Fatal(err) + } + log.Println("Closed", tmpfilename) + + log.Println("Opening", tmpfilename) + buffer, err := ioutil.ReadFile(tmpfilename) + if err != nil { + log.Fatal(err) + } + log.Println("Read[[", string(buffer), "]]") +} diff --git a/idioms/139_create_temp_directory/139_create_temp_directory.go b/idioms/139_create_temp_directory/139_create_temp_directory.go new file mode 100644 index 0000000..3a98e01 --- /dev/null +++ b/idioms/139_create_temp_directory/139_create_temp_directory.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" +) + +func main() { + content := []byte("temporary file's content") + dir, err := ioutil.TempDir("", "") + if err != nil { + log.Fatal(err) + } + + defer os.RemoveAll(dir) // clean up + + inspect(dir) + + tmpfn := filepath.Join(dir, "tmpfile") + err = ioutil.WriteFile(tmpfn, content, 0666) + if err != nil { + log.Fatal(err) + } + + inspect(dir) +} + +func inspect(dirpath string) { + files, err := ioutil.ReadDir(dirpath) + if err != nil { + log.Fatal(err) + } + fmt.Println(dirpath, "contains", len(files), "files") +} diff --git a/idioms/140_delete_map_entry/140_delete_map_entry.go b/idioms/140_delete_map_entry/140_delete_map_entry.go new file mode 100644 index 0000000..29bbcb1 --- /dev/null +++ b/idioms/140_delete_map_entry/140_delete_map_entry.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +func main() { + m := map[string]int{ + "uno": 1, + "dos": 2, + "tres": 3, + } + + delete(m, "dos") + delete(m, "cinco") + + fmt.Println(m) +} \ No newline at end of file diff --git a/idioms/141_iterate_in_sequence_over_two_lists/141_iterate_in_sequence_over_two_lists.go b/idioms/141_iterate_in_sequence_over_two_lists/141_iterate_in_sequence_over_two_lists.go new file mode 100644 index 0000000..1c5b6c2 --- /dev/null +++ b/idioms/141_iterate_in_sequence_over_two_lists/141_iterate_in_sequence_over_two_lists.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" +) + +func main() { + items1 := []string{"a", "b", "c"} + items2 := []string{"A", "B", "C"} + + for _, v := range items1 { + fmt.Println(v) + } + for _, v := range items2 { + fmt.Println(v) + } +} diff --git a/idioms/142a_hexadecimal_digits_of_an_integer/142a_hexadecimal_digits_of_an_integer.go b/idioms/142a_hexadecimal_digits_of_an_integer/142a_hexadecimal_digits_of_an_integer.go new file mode 100644 index 0000000..d5ef995 --- /dev/null +++ b/idioms/142a_hexadecimal_digits_of_an_integer/142a_hexadecimal_digits_of_an_integer.go @@ -0,0 +1,11 @@ +package main + +import "fmt" +import "strconv" + +func main() { + x := int64(999) + s := strconv.FormatInt(x, 16) + + fmt.Println(s) +} diff --git a/idioms/142b_hexadecimal_digits_of_an_integer/142b_hexadecimal_digits_of_an_integer.go b/idioms/142b_hexadecimal_digits_of_an_integer/142b_hexadecimal_digits_of_an_integer.go new file mode 100644 index 0000000..723f7a9 --- /dev/null +++ b/idioms/142b_hexadecimal_digits_of_an_integer/142b_hexadecimal_digits_of_an_integer.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + x := big.NewInt(999) + s := fmt.Sprintf("%x", x) + + fmt.Println(s) +} diff --git a/idioms/143_iterate_alternatively_over_two_lists/143_iterate_alternatively_over_two_lists.go b/idioms/143_iterate_alternatively_over_two_lists/143_iterate_alternatively_over_two_lists.go new file mode 100644 index 0000000..6640985 --- /dev/null +++ b/idioms/143_iterate_alternatively_over_two_lists/143_iterate_alternatively_over_two_lists.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" +) + +func main() { + items1 := []string{"a", "b"} + items2 := []string{"A", "B", "C"} + + for i := 0; i < len(items1) || i < len(items2); i++ { + if i < len(items1) { + fmt.Println(items1[i]) + } + if i < len(items2) { + fmt.Println(items2[i]) + } + } +} diff --git a/idioms/144_check_if_file_exists/144_check_if_file_exists.go b/idioms/144_check_if_file_exists/144_check_if_file_exists.go new file mode 100644 index 0000000..935838b --- /dev/null +++ b/idioms/144_check_if_file_exists/144_check_if_file_exists.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" +) + +func main() { + fp := "foo.txt" + _, err := os.Stat(fp) + b := !os.IsNotExist(err) + fmt.Println(fp, "exists:", b) + + fp = "bar.txt" + _, err = os.Stat(fp) + b = !os.IsNotExist(err) + fmt.Println(fp, "exists:", b) +} + +func init() { + ioutil.WriteFile("foo.txt", []byte(`abc`), 0644) +} diff --git a/idioms/145_print_log_line_with_datetime/145_print_log_line_with_datetime.go b/idioms/145_print_log_line_with_datetime/145_print_log_line_with_datetime.go new file mode 100644 index 0000000..46f9d8b --- /dev/null +++ b/idioms/145_print_log_line_with_datetime/145_print_log_line_with_datetime.go @@ -0,0 +1,12 @@ +package main + +import "log" + +func main() { + msg := "Hello, playground" + log.Println(msg) + + // The date is fixed in the past in the Playground, never mind. +} + +// See http://www.programming-idioms.org/idiom/145/print-log-line-with-date/1815/go diff --git a/idioms/146_convert_string_to_floating_point_number/146_convert_string_to_floating_point_number.go b/idioms/146_convert_string_to_floating_point_number/146_convert_string_to_floating_point_number.go new file mode 100644 index 0000000..51e6551 --- /dev/null +++ b/idioms/146_convert_string_to_floating_point_number/146_convert_string_to_floating_point_number.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "strconv" +) + +func main() { + s := "3.1415926535" + + f, err := strconv.ParseFloat(s, 64) + fmt.Printf("%T, %v, err=%v\n", f, f, err) +} + +// +// http://www.programming-idioms.org/idiom/146/convert-string-to-floating-point-number/1819/go +// diff --git a/idioms/147a_remove_all_non_ascii_characters/147a_remove_all_non_ascii_characters.go b/idioms/147a_remove_all_non_ascii_characters/147a_remove_all_non_ascii_characters.go new file mode 100644 index 0000000..d185b1c --- /dev/null +++ b/idioms/147a_remove_all_non_ascii_characters/147a_remove_all_non_ascii_characters.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "regexp" +) + +func main() { + s := "dæmi : пример : příklad : thí dụ" + + re := regexp.MustCompile("[[:^ascii:]]") + t := re.ReplaceAllLiteralString(s, "") + + fmt.Println(t) +} diff --git a/idioms/147b_remove_all_non_ascii_characters/147b_remove_all_non_ascii_characters.go b/idioms/147b_remove_all_non_ascii_characters/147b_remove_all_non_ascii_characters.go new file mode 100644 index 0000000..908d14c --- /dev/null +++ b/idioms/147b_remove_all_non_ascii_characters/147b_remove_all_non_ascii_characters.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "strings" + "unicode" +) + +func main() { + s := "5#∑∂ƒ∞645eyfu" + t := strings.Map(func(r rune) rune { + if r > unicode.MaxASCII { + return -1 + } + return r + }, s) + fmt.Println(t) +} diff --git a/idioms/148_read_list_of_integers_from_stdin/148_read_list_of_integers_from_stdin.go b/idioms/148_read_list_of_integers_from_stdin/148_read_list_of_integers_from_stdin.go new file mode 100644 index 0000000..d78d13c --- /dev/null +++ b/idioms/148_read_list_of_integers_from_stdin/148_read_list_of_integers_from_stdin.go @@ -0,0 +1,31 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "strconv" + "strings" +) + +func main() { + var ints []int + s := bufio.NewScanner(osStdin) + s.Split(bufio.ScanWords) + for s.Scan() { + i, err := strconv.Atoi(s.Text()) + if err == nil { + ints = append(ints, i) + } + } + if err := s.Err(); err != nil { + log.Fatal(err) + } + fmt.Println(ints) +} + +// osStdin simulates os.Stdin +var osStdin = strings.NewReader(` +11 +22 +33 `) diff --git a/idioms/150_remove_trailing_slash/150_remove_trailing_slash.go b/idioms/150_remove_trailing_slash/150_remove_trailing_slash.go new file mode 100644 index 0000000..a59ce70 --- /dev/null +++ b/idioms/150_remove_trailing_slash/150_remove_trailing_slash.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + p := "/usr/bin/" + + p = strings.TrimSuffix(p, "/") + + fmt.Println(p) +} diff --git a/idioms/151a_remove_string_trailing_path_separator/151a_remove_string_trailing_path_separator.go b/idioms/151a_remove_string_trailing_path_separator/151a_remove_string_trailing_path_separator.go new file mode 100644 index 0000000..5a91de4 --- /dev/null +++ b/idioms/151a_remove_string_trailing_path_separator/151a_remove_string_trailing_path_separator.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" + "strings" +) + +func main() { + p := somePath() + fmt.Println(p) + + sep := fmt.Sprintf("%c", os.PathSeparator) + p = strings.TrimSuffix(p, sep) + + fmt.Println(p) +} + +func somePath() string { + dir, err := ioutil.TempDir("", "") + if err != nil { + panic(err) + } + p := fmt.Sprintf("%s%c%s%c", dir, os.PathSeparator, "foobar", os.PathSeparator) + return p +} diff --git a/idioms/151b_remove_string_trailing_path_separator/151b_remove_string_trailing_path_separator.go b/idioms/151b_remove_string_trailing_path_separator/151b_remove_string_trailing_path_separator.go new file mode 100644 index 0000000..e9c8f6d --- /dev/null +++ b/idioms/151b_remove_string_trailing_path_separator/151b_remove_string_trailing_path_separator.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strings" +) + +func main() { + p := somePath() + fmt.Println(p) + + sep := fmt.Sprintf("%c", filepath.Separator) + p = strings.TrimSuffix(p, sep) + + fmt.Println(p) +} + +func somePath() string { + dir, err := ioutil.TempDir("", "") + if err != nil { + panic(err) + } + p := fmt.Sprintf("%s%c%s%c", dir, os.PathSeparator, "foobar", os.PathSeparator) + return p +} diff --git a/idioms/152_turn_a_character_into_a_string/152_turn_a_character_into_a_string.go b/idioms/152_turn_a_character_into_a_string/152_turn_a_character_into_a_string.go new file mode 100644 index 0000000..a9e2c7d --- /dev/null +++ b/idioms/152_turn_a_character_into_a_string/152_turn_a_character_into_a_string.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + var c rune = os.PathSeparator + fmt.Printf("%c \n", c) + + s := fmt.Sprintf("%c", c) + fmt.Printf("%#v \n", s) +} diff --git a/idioms/153a_concatenate_string_with_integer/153a_concatenate_string_with_integer.go b/idioms/153a_concatenate_string_with_integer/153a_concatenate_string_with_integer.go new file mode 100644 index 0000000..c58eb22 --- /dev/null +++ b/idioms/153a_concatenate_string_with_integer/153a_concatenate_string_with_integer.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + s := "Hello" + i := 123 + + t := fmt.Sprintf("%s%d", s, i) + + fmt.Println(t) +} diff --git a/idioms/153b_concatenate_string_with_integer/153b_concatenate_string_with_integer.go b/idioms/153b_concatenate_string_with_integer/153b_concatenate_string_with_integer.go new file mode 100644 index 0000000..9956e21 --- /dev/null +++ b/idioms/153b_concatenate_string_with_integer/153b_concatenate_string_with_integer.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "strconv" +) + +func main() { + s := "Hello" + i := 123 + + t := s + strconv.Itoa(i) + + fmt.Println(t) +} diff --git a/idioms/154a_halfway_between_two_hex_color_codes/154a_halfway_between_two_hex_color_codes.go b/idioms/154a_halfway_between_two_hex_color_codes/154a_halfway_between_two_hex_color_codes.go new file mode 100644 index 0000000..1ce5ee6 --- /dev/null +++ b/idioms/154a_halfway_between_two_hex_color_codes/154a_halfway_between_two_hex_color_codes.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "strconv" + "strings" +) + +// For concision, halfway assume valid inputs. +// Caller must have explicitly checked that c1, c2 are well-formed color codes. +func halfway(c1, c2 string) string { + r1, _ := strconv.ParseInt(c1[1:3], 16, 0) + r2, _ := strconv.ParseInt(c2[1:3], 16, 0) + r := (r1 + r2) / 2 + + g1, _ := strconv.ParseInt(c1[3:5], 16, 0) + g2, _ := strconv.ParseInt(c2[3:5], 16, 0) + g := (g1 + g2) / 2 + + b1, _ := strconv.ParseInt(c1[5:7], 16, 0) + b2, _ := strconv.ParseInt(c2[5:7], 16, 0) + b := (b1 + b2) / 2 + + c := fmt.Sprintf("#%02X%02X%02X", r, g, b) + return c +} + +func main() { + c1 := "#15293E" + c2 := "#012549" + + if err := checkFormat(c1); err != nil { + panic(fmt.Errorf("Wrong input %q: %v", c1, err)) + } + if err := checkFormat(c2); err != nil { + panic(fmt.Errorf("Wrong input %q: %v", c2, err)) + } + + c := halfway(c1, c2) + fmt.Println("The average of", c1, "and", c2, "is", c) +} + +func checkFormat(color string) error { + if len(color) != 7 { + return fmt.Errorf("Hex colors have exactly 7 chars") + } + if color[0] != '#' { + return fmt.Errorf("Hex colors start with #") + } + isNotDigit := func(c rune) bool { return (c < '0' || c > '9') && (c < 'a' || c > 'f') } + if strings.IndexFunc(strings.ToLower(color[1:]), isNotDigit) != -1 { + return fmt.Errorf("Forbidden char") + } + return nil +} diff --git a/idioms/154b_halfway_between_two_hex_color_codes/154b_halfway_between_two_hex_color_codes.go b/idioms/154b_halfway_between_two_hex_color_codes/154b_halfway_between_two_hex_color_codes.go new file mode 100644 index 0000000..49305cc --- /dev/null +++ b/idioms/154b_halfway_between_two_hex_color_codes/154b_halfway_between_two_hex_color_codes.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "strconv" + "strings" +) + +// For concision, halfway assume valid inputs. +// Caller must have explicitly checked that c1, c2 are well-formed color codes. +func halfway(c1, c2 string) string { + var buf [7]byte + buf[0] = '#' + for i := 0; i < 3; i++ { + sub1 := c1[1+2*i : 3+2*i] + sub2 := c2[1+2*i : 3+2*i] + v1, _ := strconv.ParseInt(sub1, 16, 0) + v2, _ := strconv.ParseInt(sub2, 16, 0) + v := (v1 + v2) / 2 + sub := fmt.Sprintf("%02X", v) + copy(buf[1+2*i:3+2*i], sub) + } + c := string(buf[:]) + + return c +} + +func main() { + c1 := "#15293E" + c2 := "#012549" + + if err := checkFormat(c1); err != nil { + panic(fmt.Errorf("Wrong input %q: %v", c1, err)) + } + if err := checkFormat(c2); err != nil { + panic(fmt.Errorf("Wrong input %q: %v", c2, err)) + } + + c := halfway(c1, c2) + fmt.Println("The average of", c1, "and", c2, "is", c) +} + +func checkFormat(color string) error { + if len(color) != 7 { + return fmt.Errorf("Hex colors have exactly 7 chars") + } + if color[0] != '#' { + return fmt.Errorf("Hex colors start with #") + } + isNotDigit := func(c rune) bool { return (c < '0' || c > '9') && (c < 'a' || c > 'f') } + if strings.IndexFunc(strings.ToLower(color[1:]), isNotDigit) != -1 { + return fmt.Errorf("Forbidden char") + } + return nil +} diff --git a/idioms/155_delete_file/155_delete_file.go b/idioms/155_delete_file/155_delete_file.go new file mode 100644 index 0000000..0492377 --- /dev/null +++ b/idioms/155_delete_file/155_delete_file.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" +) + +func main() { + for _, filepath := range []string{ + "/tmp/foo.txt", + "/tmp/bar.txt", + "/tmp/foo.txt", + } { + err := os.Remove(filepath) + if err == nil { + fmt.Println("Removed", filepath) + } else { + fmt.Fprintln(os.Stderr, err) + } + } +} + +func init() { + err := ioutil.WriteFile("/tmp/foo.txt", []byte(`abc`), 0644) + if err != nil { + panic(err) + } +} diff --git a/idioms/156_format_integer_with_zero_padding/156_format_integer_with_zero_padding.go b/idioms/156_format_integer_with_zero_padding/156_format_integer_with_zero_padding.go new file mode 100644 index 0000000..9286028 --- /dev/null +++ b/idioms/156_format_integer_with_zero_padding/156_format_integer_with_zero_padding.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +func main() { + for _, i := range []int{ + 0, + 8, + 64, + 256, + 2048, + } { + s := fmt.Sprintf("%03d", i) + fmt.Println(s) + } +} diff --git a/idioms/157_declare_constant_string/157_declare_constant_string.go b/idioms/157_declare_constant_string/157_declare_constant_string.go new file mode 100644 index 0000000..c3ed1ee --- /dev/null +++ b/idioms/157_declare_constant_string/157_declare_constant_string.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" +) + +const planet = "Earth" + +func main() { + fmt.Println("We live on planet", planet) +} diff --git a/idioms/158_random_sublist/158_random_sublist.go b/idioms/158_random_sublist/158_random_sublist.go new file mode 100644 index 0000000..202c59b --- /dev/null +++ b/idioms/158_random_sublist/158_random_sublist.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + type T string + + x := []T{"Alice", "Bob", "Carol", "Dan", "Eve", "Frank", "Grace", "Heidi"} + k := 4 + + y := make([]T, k) + perm := rand.Perm(len(x)) + for i, v := range perm[:k] { + y[i] = x[v] + } + + fmt.Printf("%q", y) +} diff --git a/idioms/161_multiply_all_the_elements_of_a_list/161_multiply_all_the_elements_of_a_list.go b/idioms/161_multiply_all_the_elements_of_a_list/161_multiply_all_the_elements_of_a_list.go new file mode 100644 index 0000000..4e78ffb --- /dev/null +++ b/idioms/161_multiply_all_the_elements_of_a_list/161_multiply_all_the_elements_of_a_list.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" +) + +func main() { + const c = 5.5 + elements := []float64{2, 4, 9, 30} + fmt.Println(elements) + + for i := range elements { + elements[i] *= c + } + fmt.Println(elements) +} diff --git a/idioms/162_execute_procedures_depending_on_options/162_execute_procedures_depending_on_options.go b/idioms/162_execute_procedures_depending_on_options/162_execute_procedures_depending_on_options.go new file mode 100644 index 0000000..be757ab --- /dev/null +++ b/idioms/162_execute_procedures_depending_on_options/162_execute_procedures_depending_on_options.go @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + "os" +) + +func init() { + // Just for testing in the Playground, let's simulate + // the user called this program with command line + // flags -f and -b + os.Args = []string{"program", "-f", "-b"} +} + +var b = flag.Bool("b", false, "Do bat") +var f = flag.Bool("f", false, "Do fox") + +func main() { + flag.Parse() + if *b { + bar() + } + if *f { + fox() + } + fmt.Println("The end.") +} + +func bar() { + fmt.Println("BAR") +} + +func fox() { + fmt.Println("FOX") +} diff --git a/idioms/163_print_list_elements_by_group_of_2/163_print_list_elements_by_group_of_2.go b/idioms/163_print_list_elements_by_group_of_2/163_print_list_elements_by_group_of_2.go new file mode 100644 index 0000000..5e52cfe --- /dev/null +++ b/idioms/163_print_list_elements_by_group_of_2/163_print_list_elements_by_group_of_2.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" +) + +func main() { + list := []string{"a", "b", "c", "d", "e", "f"} + + for i := 0; i+1 < len(list); i += 2 { + fmt.Println(list[i], list[i+1]) + } +} diff --git a/idioms/165_last_element_of_list/165_last_element_of_list.go b/idioms/165_last_element_of_list/165_last_element_of_list.go new file mode 100644 index 0000000..eddc786 --- /dev/null +++ b/idioms/165_last_element_of_list/165_last_element_of_list.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []string{ "what", "a", "mess" } + + x := items[len(items)-1] + + fmt.Println(x) +} diff --git a/idioms/166a_concatenate_two_lists/166a_concatenate_two_lists.go b/idioms/166a_concatenate_two_lists/166a_concatenate_two_lists.go new file mode 100644 index 0000000..cf959d6 --- /dev/null +++ b/idioms/166a_concatenate_two_lists/166a_concatenate_two_lists.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + a := []string{"The ", "quick "} + b := []string{"brown ", "fox "} + + ab := append(a, b...) + + fmt.Printf("%q", ab) +} diff --git a/idioms/166b_concatenate_two_lists/166b_concatenate_two_lists.go b/idioms/166b_concatenate_two_lists/166b_concatenate_two_lists.go new file mode 100644 index 0000000..a55f738 --- /dev/null +++ b/idioms/166b_concatenate_two_lists/166b_concatenate_two_lists.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" +) + +func main() { + type T string + + a := []T{"The ", "quick "} + b := []T{"brown ", "fox "} + + var ab []T + ab = append(append(ab, a...), b...) + + fmt.Printf("%q", ab) +} diff --git a/idioms/166c_concatenate_two_lists/166c_concatenate_two_lists.go b/idioms/166c_concatenate_two_lists/166c_concatenate_two_lists.go new file mode 100644 index 0000000..b5dbed1 --- /dev/null +++ b/idioms/166c_concatenate_two_lists/166c_concatenate_two_lists.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +func main() { + type T string + + a := []T{"The ", "quick "} + b := []T{"brown ", "fox "} + + ab := make([]T, len(a)+len(b)) + copy(ab, a) + copy(ab[len(a):], b) + + fmt.Printf("%q", ab) +} diff --git a/idioms/167_trim_prefix/167_trim_prefix.go b/idioms/167_trim_prefix/167_trim_prefix.go new file mode 100644 index 0000000..2d6cf80 --- /dev/null +++ b/idioms/167_trim_prefix/167_trim_prefix.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "café-society" + p := "café" + + t := strings.TrimPrefix(s, p) + + fmt.Println(t) +} diff --git a/idioms/168_trim_suffix/168_trim_suffix.go b/idioms/168_trim_suffix/168_trim_suffix.go new file mode 100644 index 0000000..1b29735 --- /dev/null +++ b/idioms/168_trim_suffix/168_trim_suffix.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "café-society" + w := "society" + + t := strings.TrimSuffix(s, w) + + fmt.Println(t) +} diff --git a/idioms/169_string_length/169_string_length.go b/idioms/169_string_length/169_string_length.go new file mode 100644 index 0000000..a320f52 --- /dev/null +++ b/idioms/169_string_length/169_string_length.go @@ -0,0 +1,11 @@ +package main + +import "fmt" +import "unicode/utf8" + +func main() { + s := "Hello, 世界" + n := utf8.RuneCountInString(s) + + fmt.Println(n) +} diff --git a/idioms/170_get_map_size/170_get_map_size.go b/idioms/170_get_map_size/170_get_map_size.go new file mode 100644 index 0000000..4020db2 --- /dev/null +++ b/idioms/170_get_map_size/170_get_map_size.go @@ -0,0 +1,9 @@ +package main + +import "fmt" + +func main() { + mymap := map[string]int{"a": 1, "b": 2, "c": 3} + n := len(mymap) + fmt.Println(n) +} diff --git a/idioms/171_add_an_element_at_the_end_of_a_list/171_add_an_element_at_the_end_of_a_list.go b/idioms/171_add_an_element_at_the_end_of_a_list/171_add_an_element_at_the_end_of_a_list.go new file mode 100644 index 0000000..c73567d --- /dev/null +++ b/idioms/171_add_an_element_at_the_end_of_a_list/171_add_an_element_at_the_end_of_a_list.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func main() { + s := []int{1, 1, 2, 3, 5, 8, 13} + x := 21 + + s = append(s, x) + + fmt.Println(s) +} diff --git a/idioms/172_insert_an_entry_in_a_map/172_insert_an_entry_in_a_map.go b/idioms/172_insert_an_entry_in_a_map/172_insert_an_entry_in_a_map.go new file mode 100644 index 0000000..2be2dc7 --- /dev/null +++ b/idioms/172_insert_an_entry_in_a_map/172_insert_an_entry_in_a_map.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +func main() { + m := map[string]int{"one": 1, "two": 2} + k := "three" + v := 3 + + m[k] = v + + fmt.Println(m) +} diff --git a/idioms/174a_make_http_post_request/174a_make_http_post_request.go b/idioms/174a_make_http_post_request/174a_make_http_post_request.go new file mode 100644 index 0000000..d49b6b5 --- /dev/null +++ b/idioms/174a_make_http_post_request/174a_make_http_post_request.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "io" + "io/ioutil" + "net" + "net/http" +) + +func main() { + contentType := "text/plain" + var body io.Reader + u := "http://" + localhost + "/hello" + + response, err := http.Post(u, contentType, body) + check(err) + buffer, err := ioutil.ReadAll(response.Body) + check(err) + fmt.Println("POST response:", response.StatusCode, string(buffer)) + + response, err = http.Get(u) + check(err) + buffer, err = ioutil.ReadAll(response.Body) + check(err) + fmt.Println("GET response:", response.StatusCode, string(buffer)) +} + +const localhost = "127.0.0.1:3000" + +func init() { + http.HandleFunc("/hello", myHandler) + startServer() +} + +func myHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Refusing request verb %q", r.Method) + return + } + fmt.Fprintf(w, "Hello POST :)") +} + +func startServer() { + listener, err := net.Listen("tcp", localhost) + check(err) + + go http.Serve(listener, nil) +} + +func check(err error) { + if err != nil { + panic(err) + } +} diff --git a/idioms/174b_make_http_post_request/174b_make_http_post_request.go b/idioms/174b_make_http_post_request/174b_make_http_post_request.go new file mode 100644 index 0000000..aaa11bf --- /dev/null +++ b/idioms/174b_make_http_post_request/174b_make_http_post_request.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "io/ioutil" + "net" + "net/http" + "net/url" +) + +func main() { + formValues := url.Values{ + "who": []string{"Alice"}, + } + u := "http://" + localhost + "/hello" + + response, err := http.PostForm(u, formValues) + check(err) + buffer, err := ioutil.ReadAll(response.Body) + check(err) + fmt.Println("POST response:", response.StatusCode, string(buffer)) + + response, err = http.Get(u) + check(err) + buffer, err = ioutil.ReadAll(response.Body) + check(err) + fmt.Println("GET response:", response.StatusCode, string(buffer)) +} + +const localhost = "127.0.0.1:3000" + +func init() { + http.HandleFunc("/hello", myHandler) + startServer() +} + +func myHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Refusing request verb %q", r.Method) + return + } + fmt.Fprintf(w, "Hello %s (POST)", r.FormValue("who")) +} + +func startServer() { + listener, err := net.Listen("tcp", localhost) + check(err) + + go http.Serve(listener, nil) +} + +func check(err error) { + if err != nil { + panic(err) + } +} diff --git a/idioms/175a_bytes_to_hex_string/175a_bytes_to_hex_string.go b/idioms/175a_bytes_to_hex_string/175a_bytes_to_hex_string.go new file mode 100644 index 0000000..f6c9669 --- /dev/null +++ b/idioms/175a_bytes_to_hex_string/175a_bytes_to_hex_string.go @@ -0,0 +1,14 @@ +package main + +import ( + "encoding/hex" + "fmt" +) + +func main() { + a := []byte("Hello") + + s := hex.EncodeToString(a) + + fmt.Println(s) +} diff --git a/idioms/175b_bytes_to_hex_string/175b_bytes_to_hex_string.go b/idioms/175b_bytes_to_hex_string/175b_bytes_to_hex_string.go new file mode 100644 index 0000000..6a08e5c --- /dev/null +++ b/idioms/175b_bytes_to_hex_string/175b_bytes_to_hex_string.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" +) + +func main() { + a := []byte("Hello") + + s := fmt.Sprintf("%x", a) + + fmt.Println(s) +} diff --git a/idioms/176_hex_string_to_byte_array/176_hex_string_to_byte_array.go b/idioms/176_hex_string_to_byte_array/176_hex_string_to_byte_array.go new file mode 100644 index 0000000..81afdc5 --- /dev/null +++ b/idioms/176_hex_string_to_byte_array/176_hex_string_to_byte_array.go @@ -0,0 +1,19 @@ +package main + +import ( + "encoding/hex" + "fmt" + "log" +) + +func main() { + s := "48656c6c6f" + + a, err := hex.DecodeString(s) + if err != nil { + log.Fatal(err) + } + + fmt.Println(a) + fmt.Println(string(a)) +} diff --git a/idioms/177_find_files_with_a_given_list_of_filename_extensions/177_find_files_with_a_given_list_of_filename_extensions.go b/idioms/177_find_files_with_a_given_list_of_filename_extensions/177_find_files_with_a_given_list_of_filename_extensions.go new file mode 100644 index 0000000..ee64793 --- /dev/null +++ b/idioms/177_find_files_with_a_given_list_of_filename_extensions/177_find_files_with_a_given_list_of_filename_extensions.go @@ -0,0 +1,76 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strings" +) + +func main() { + D, err := prepareTestDirTree() + if err != nil { + fmt.Printf("unable to create test dir tree: %v\n", err) + return + } + defer os.RemoveAll(D) + + L := []string{} + err = filepath.Walk(D, func(path string, info os.FileInfo, err error) error { + if err != nil { + fmt.Printf("failure accessing a path %q: %v\n", path, err) + return err + } + for _, ext := range []string{".jpg", ".jpeg", ".png"} { + if strings.HasSuffix(path, ext) { + L = append(L, path) + break + } + } + return nil + }) + + fmt.Println(err) + fmt.Println(strings.Join(L, "\n")) +} + +func prepareTestDirTree() (string, error) { + tmpDir, err := ioutil.TempDir("", "") + if err != nil { + return "", fmt.Errorf("error creating temp directory: %v\n", err) + } + + for _, subdir := range []string{ + "2018/nov", + "2018/dec", + "2019/jan", + "2019/feb", + } { + err = os.MkdirAll(filepath.Join(tmpDir, subdir), 0755) + if err != nil { + os.RemoveAll(tmpDir) + return "", err + } + } + + for _, fpath := range []string{ + "2018/nov/a.txt", + "2018/nov/b.jpg", + "2018/c.png", + "2019/jan/d.mp3", + "2019/jan/e.jpg", + "2019/jan/f.jpeg", + "2019/feb/g.jpg", + "2019/feb/g.jpeg", + "h.jpg", + } { + _, err := os.Create(filepath.Join(tmpDir, fpath)) + if err != nil { + os.RemoveAll(tmpDir) + return "", err + } + } + + return tmpDir, nil +} diff --git a/idioms/178_check_if_point_is_inside_rectangle/178_check_if_point_is_inside_rectangle.go b/idioms/178_check_if_point_is_inside_rectangle/178_check_if_point_is_inside_rectangle.go new file mode 100644 index 0000000..6c84643 --- /dev/null +++ b/idioms/178_check_if_point_is_inside_rectangle/178_check_if_point_is_inside_rectangle.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "image" +) + +func main() { + x1, y1, x2, y2 := 1, 1, 50, 100 + r := image.Rect(x1, y1, x2, y2) + + x, y := 10, 10 + p := image.Pt(x, y) + b := p.In(r) + fmt.Println(b) + + x, y = 100, 100 + p = image.Pt(x, y) + b = p.In(r) + fmt.Println(b) +} diff --git a/idioms/180_list_files_in_directory/180_list_files_in_directory.go b/idioms/180_list_files_in_directory/180_list_files_in_directory.go new file mode 100644 index 0000000..709b9cd --- /dev/null +++ b/idioms/180_list_files_in_directory/180_list_files_in_directory.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" +) + +func main() { + d := "/" + + x, err := ioutil.ReadDir(d) + if err != nil { + log.Fatal(err) + } + + for _, f := range x { + fmt.Println(f.Name()) + } +} diff --git a/idioms/182_quine_program/182_quine_program.go b/idioms/182_quine_program/182_quine_program.go new file mode 100644 index 0000000..474e2f9 --- /dev/null +++ b/idioms/182_quine_program/182_quine_program.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func main() { + fmt.Printf("%s%c%s%c\n", s, 0x60, s, 0x60) +} + +var s = `package main + +import "fmt" + +func main() { + fmt.Printf("%s%c%s%c\n", s, 0x60, s, 0x60) +} + +var s = ` diff --git a/idioms/183_make_http_put_request/183_make_http_put_request.go b/idioms/183_make_http_put_request/183_make_http_put_request.go new file mode 100644 index 0000000..3549c12 --- /dev/null +++ b/idioms/183_make_http_put_request/183_make_http_put_request.go @@ -0,0 +1,67 @@ +package main + +import ( + "fmt" + "log" + "strings" + + "io/ioutil" + "net" + "net/http" +) + +func main() { + contentType := "text/plain" + bodyString := "This is my request payload" + contentLength := int64(len(bodyString)) + body := strings.NewReader(bodyString) + u := "http://" + localhost + "/hello" + + req, err := http.NewRequest("PUT", u, body) + if err != nil { + log.Fatal(err) + } + req.Header.Set("Content-Type", contentType) + req.ContentLength = contentLength + response, err := http.DefaultClient.Do(req) + + check(err) + buffer, err := ioutil.ReadAll(response.Body) + check(err) + fmt.Println("POST response:", response.StatusCode, string(buffer)) + + response, err = http.Get(u) + check(err) + buffer, err = ioutil.ReadAll(response.Body) + check(err) + fmt.Println("GET response:", response.StatusCode, string(buffer)) +} + +const localhost = "127.0.0.1:3000" + +func init() { + http.HandleFunc("/hello", myHandler) + startServer() +} + +func myHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "PUT" { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "Refusing request verb %q", r.Method) + return + } + fmt.Fprintf(w, "Hello PUT :)") +} + +func startServer() { + listener, err := net.Listen("tcp", localhost) + check(err) + + go http.Serve(listener, nil) +} + +func check(err error) { + if err != nil { + panic(err) + } +} diff --git a/idioms/184_tomorrow/184_tomorrow.go b/idioms/184_tomorrow/184_tomorrow.go new file mode 100644 index 0000000..52ecc79 --- /dev/null +++ b/idioms/184_tomorrow/184_tomorrow.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + // "2006-01-02" is actually a layout. See https://pkg.go.dev/time#Time.String + + t := time.Now().Add(24 * time.Hour).Format("2006-01-02") + + // In the Go Playground, this prints "2009-11-11" because the simulated "current date" is fixed at 2009-11-10. + fmt.Println(t) +} diff --git a/idioms/185a_execute_function_in_30_seconds/185a_execute_function_in_30_seconds.go b/idioms/185a_execute_function_in_30_seconds/185a_execute_function_in_30_seconds.go new file mode 100644 index 0000000..1066ca1 --- /dev/null +++ b/idioms/185a_execute_function_in_30_seconds/185a_execute_function_in_30_seconds.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + fmt.Println("Scheduling f(42)") + + timer := time.AfterFunc( + 3*time.Second, + func() { + f(42) + }) + + // This time.Timer could be used to cancel the call. + _ = timer + + // Poor man's waiting of completion of f. + // Don't do this in prod, use proper synchronization instead. + time.Sleep(4 * time.Second) +} + +func f(i int) { + fmt.Println("Received", i) +} diff --git a/idioms/185b_execute_function_in_30_seconds/185b_execute_function_in_30_seconds.go b/idioms/185b_execute_function_in_30_seconds/185b_execute_function_in_30_seconds.go new file mode 100644 index 0000000..9a74895 --- /dev/null +++ b/idioms/185b_execute_function_in_30_seconds/185b_execute_function_in_30_seconds.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + fmt.Println("Scheduling f(42)") + + go func() { + time.Sleep(3 * time.Second) + f(42) + }() + + // Poor man's waiting of completion of f. + // Don't do this in prod, use proper synchronization instead. + time.Sleep(4 * time.Second) +} + +func f(i int) { + fmt.Println("Received", i) +} diff --git a/idioms/186a_exit_program_cleanly/186a_exit_program_cleanly.go b/idioms/186a_exit_program_cleanly/186a_exit_program_cleanly.go new file mode 100644 index 0000000..d64830a --- /dev/null +++ b/idioms/186a_exit_program_cleanly/186a_exit_program_cleanly.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + fmt.Println("A") + os.Exit(0) + fmt.Println("B") +} diff --git a/idioms/186b_exit_program_cleanly/186b_exit_program_cleanly.go b/idioms/186b_exit_program_cleanly/186b_exit_program_cleanly.go new file mode 100644 index 0000000..59eadcb --- /dev/null +++ b/idioms/186b_exit_program_cleanly/186b_exit_program_cleanly.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + process1() + process2() + process3() +} + +func process1() { + fmt.Println("process 1") +} + +func process2() { + fmt.Println("process 2") + defer fmt.Println("A") + defer os.Exit(0) + defer fmt.Println("B") + fmt.Println("C") +} + +func process3() { + fmt.Println("process 3") +} diff --git a/idioms/189_filter_and_transform_list/189_filter_and_transform_list.go b/idioms/189_filter_and_transform_list/189_filter_and_transform_list.go new file mode 100644 index 0000000..0c15ec0 --- /dev/null +++ b/idioms/189_filter_and_transform_list/189_filter_and_transform_list.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" +) + +func P(e int) bool { + // Predicate "is even" + return e%2 == 0 +} + +type Result = int + +func T(e int) Result { + // Transformation "square" + return e * e +} + +func main() { + x := []int{4, 5, 6, 7, 8, 9, 10} + + var y []Result + for _, e := range x { + if P(e) { + y = append(y, T(e)) + } + } + + fmt.Println(y) +} \ No newline at end of file diff --git a/idioms/191_check_if_any_value_in_a_list_is_larger_than_a_limit/191_check_if_any_value_in_a_list_is_larger_than_a_limit.go b/idioms/191_check_if_any_value_in_a_list_is_larger_than_a_limit/191_check_if_any_value_in_a_list_is_larger_than_a_limit.go new file mode 100644 index 0000000..8003b73 --- /dev/null +++ b/idioms/191_check_if_any_value_in_a_list_is_larger_than_a_limit/191_check_if_any_value_in_a_list_is_larger_than_a_limit.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" +) + +func f() { + fmt.Println("Larger found") +} + +func main() { + a := []int{1, 2, 3, 4, 5} + x := 4 + for _, v := range a { + if v > x { + f() + break + } + } +} \ No newline at end of file diff --git a/idioms/192_declare_a_real_variable_with_at_least_20_digits/192_declare_a_real_variable_with_at_least_20_digits.go b/idioms/192_declare_a_real_variable_with_at_least_20_digits/192_declare_a_real_variable_with_at_least_20_digits.go new file mode 100644 index 0000000..ff60c51 --- /dev/null +++ b/idioms/192_declare_a_real_variable_with_at_least_20_digits/192_declare_a_real_variable_with_at_least_20_digits.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + a, _, err := big.ParseFloat("123456789.123456789123465789", 10, 200, big.ToZero) + if err != nil { + panic(err) + } + + fmt.Println(a) +} diff --git a/idioms/197_get_a_list_of_lines_from_a_file/197_get_a_list_of_lines_from_a_file.go b/idioms/197_get_a_list_of_lines_from_a_file/197_get_a_list_of_lines_from_a_file.go new file mode 100644 index 0000000..5b17a8e --- /dev/null +++ b/idioms/197_get_a_list_of_lines_from_a_file/197_get_a_list_of_lines_from_a_file.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" + "strings" +) + +func readLines(path string) ([]string, error) { + b, err := ioutil.ReadFile(path) + if err != nil { + return nil, err + } + lines := strings.Split(string(b), "\n") + return lines, nil +} + +func main() { + lines, err := readLines("/tmp/file1") + if err != nil { + log.Fatalln(err) + } + + for i, line := range lines { + fmt.Printf("line %d: %s\n", i, line) + } +} + +func init() { + data := []byte(`foo +bar +baz`) + err := ioutil.WriteFile("/tmp/file1", data, 0644) + if err != nil { + log.Fatalln(err) + } +} \ No newline at end of file diff --git a/idioms/198_abort_program_execution_with_error_condition/198_abort_program_execution_with_error_condition.go b/idioms/198_abort_program_execution_with_error_condition/198_abort_program_execution_with_error_condition.go new file mode 100644 index 0000000..cedad87 --- /dev/null +++ b/idioms/198_abort_program_execution_with_error_condition/198_abort_program_execution_with_error_condition.go @@ -0,0 +1,10 @@ +package main + +import ( + "os" +) + +func main() { + x := 1 + os.Exit(x) +} diff --git a/idioms/199_truncate_a_file_at_the_current_file_position/199_truncate_a_file_at_the_current_file_position.go b/idioms/199_truncate_a_file_at_the_current_file_position/199_truncate_a_file_at_the_current_file_position.go new file mode 100644 index 0000000..cd84a8a --- /dev/null +++ b/idioms/199_truncate_a_file_at_the_current_file_position/199_truncate_a_file_at_the_current_file_position.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "io/ioutil" + "os" +) + +const F = "/tmp/data.txt" + +func init() { + err := ioutil.WriteFile(F, []byte("abcdefghij"), 0644) + if err != nil { + panic(err) + } +} + +func main() { + var position int64 = 5 + + err := os.Truncate(F, position) + if err != nil { + panic(err) + } + + buffer, err := ioutil.ReadFile(F) + if err != nil { + panic(err) + } + + fmt.Printf("%s has length %d and contents %q\n", F, len(buffer), buffer) +} diff --git a/idioms/202_sum_of_squares/202_sum_of_squares.go b/idioms/202_sum_of_squares/202_sum_of_squares.go new file mode 100644 index 0000000..7a30353 --- /dev/null +++ b/idioms/202_sum_of_squares/202_sum_of_squares.go @@ -0,0 +1,14 @@ +package main + +import ( + "math" +) + +func main() { + data := []float64{0.06, 0.82, -0.01, -0.34, -0.55} + var s float64 + for _, d := range data { + s += math.Pow(d, 2) + } + println(s) +} diff --git a/idioms/204_return_fraction_and_exponent_of_a_real_number/204_return_fraction_and_exponent_of_a_real_number.go b/idioms/204_return_fraction_and_exponent_of_a_real_number/204_return_fraction_and_exponent_of_a_real_number.go new file mode 100644 index 0000000..e6b7d16 --- /dev/null +++ b/idioms/204_return_fraction_and_exponent_of_a_real_number/204_return_fraction_and_exponent_of_a_real_number.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + a := 3.14 + + fmt.Println(math.Frexp(a)) +} diff --git a/idioms/205a_get_an_environment_variable/205a_get_an_environment_variable.go b/idioms/205a_get_an_environment_variable/205a_get_an_environment_variable.go new file mode 100644 index 0000000..1a5cae1 --- /dev/null +++ b/idioms/205a_get_an_environment_variable/205a_get_an_environment_variable.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + foo, ok := os.LookupEnv("FOO") + if !ok { + foo = "none" + } + + fmt.Println(foo) +} \ No newline at end of file diff --git a/idioms/205b_get_an_environment_variable/205b_get_an_environment_variable.go b/idioms/205b_get_an_environment_variable/205b_get_an_environment_variable.go new file mode 100644 index 0000000..09750ea --- /dev/null +++ b/idioms/205b_get_an_environment_variable/205b_get_an_environment_variable.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + foo := os.Getenv("FOO") + if foo == "" { + foo = "none" + } + + fmt.Println(foo) +} \ No newline at end of file diff --git a/idioms/206_switch_statement_with_strings/206_switch_statement_with_strings.go b/idioms/206_switch_statement_with_strings/206_switch_statement_with_strings.go new file mode 100644 index 0000000..7bbd917 --- /dev/null +++ b/idioms/206_switch_statement_with_strings/206_switch_statement_with_strings.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" +) + +func main() { + str := "baz" + + switch str { + case "foo": + foo() + case "bar": + bar() + case "baz": + baz() + case "barfl": + barfl() + } +} + +func foo() { + fmt.Println("Called foo") +} + +func bar() { + fmt.Println("Called bar") +} + +func baz() { + fmt.Println("Called baz") +} + +func barfl() { + fmt.Println("Called barfl") +} diff --git a/idioms/208_formula_with_arrays/208_formula_with_arrays.go b/idioms/208_formula_with_arrays/208_formula_with_arrays.go new file mode 100644 index 0000000..899a287 --- /dev/null +++ b/idioms/208_formula_with_arrays/208_formula_with_arrays.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "math" +) + +func applyFormula(a, b, c, d []float64, e float64) { + for i, v := range a { + a[i] = e * (v + b[i] + c[i] + math.Cos(d[i])) + } +} + +func main() { + a := []float64{1, 2, 3, 4} + b := []float64{5.5, 6.6, 7.7, 8.8} + c := []float64{9, 10, 11, 12} + d := []float64{13, 14, 15, 16} + e := 42.0 + + fmt.Println("a is ", a) + applyFormula(a, b, c, d, e) + fmt.Println("a is now", a) +} diff --git a/idioms/209_type_with_automatic_deep_deallocation/209_type_with_automatic_deep_deallocation.go b/idioms/209_type_with_automatic_deep_deallocation/209_type_with_automatic_deep_deallocation.go new file mode 100644 index 0000000..035bea0 --- /dev/null +++ b/idioms/209_type_with_automatic_deep_deallocation/209_type_with_automatic_deep_deallocation.go @@ -0,0 +1,22 @@ +package main + +func main() { + f() +} + +func f() { + type t struct { + s string + n []int + } + + v := t{ + s: "Hello, world!", + n: []int{1, 4, 9, 16, 25}, + } + + // Pretend to use v (otherwise this is a compile error) + _ = v + + // When f exits, v and all its fields are garbage-collected, recursively +} diff --git a/idioms/210_compiler_version_and_options/210_compiler_version_and_options.go b/idioms/210_compiler_version_and_options/210_compiler_version_and_options.go new file mode 100644 index 0000000..45aebd5 --- /dev/null +++ b/idioms/210_compiler_version_and_options/210_compiler_version_and_options.go @@ -0,0 +1,9 @@ +package main + +import "runtime" + +func main() { + version := runtime.Version() + + println(version) +} diff --git a/idioms/211a_create_folder/211a_create_folder.go b/idioms/211a_create_folder/211a_create_folder.go new file mode 100644 index 0000000..d781bf7 --- /dev/null +++ b/idioms/211a_create_folder/211a_create_folder.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + path := "foo" + _, err := os.Stat(path) + b := !os.IsNotExist(err) + fmt.Println(path, "exists:", b) + + err = os.Mkdir(path, os.ModeDir) + if err != nil { + panic(err) + } + + info, err2 := os.Stat(path) + b = !os.IsNotExist(err2) + fmt.Println(path, "exists:", b) + fmt.Println(path, "is a directory:", info.IsDir()) +} diff --git a/idioms/211b_create_folder/211b_create_folder.go b/idioms/211b_create_folder/211b_create_folder.go new file mode 100644 index 0000000..7c466f8 --- /dev/null +++ b/idioms/211b_create_folder/211b_create_folder.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + path := "foo/bar" + _, err := os.Stat(path) + b := !os.IsNotExist(err) + fmt.Println(path, "exists:", b) + + err = os.Mkdir(path, os.ModeDir) + if err != nil { + fmt.Println("Could not create", path, "with os.Mkdir") + } + + info, err2 := os.Stat(path) + b = !os.IsNotExist(err2) + fmt.Println(path, "exists:", b) + + err = os.MkdirAll(path, os.ModeDir) + if err != nil { + fmt.Println("Could not create", path, "with os.MkdirAll") + } + + info, err2 = os.Stat(path) + b = !os.IsNotExist(err2) + fmt.Println(path, "exists:", b) + fmt.Println(path, "is a directory:", info.IsDir()) +} diff --git a/idioms/212_check_if_folder_exists/212_check_if_folder_exists.go b/idioms/212_check_if_folder_exists/212_check_if_folder_exists.go new file mode 100644 index 0000000..aefc379 --- /dev/null +++ b/idioms/212_check_if_folder_exists/212_check_if_folder_exists.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + path := "foo" + info, err := os.Stat(path) + b := !os.IsNotExist(err) && info.IsDir() + fmt.Println(path, "is a directory:", b) + + err = os.Mkdir(path, os.ModeDir) + if err != nil { + panic(err) + } + + info, err = os.Stat(path) + b = !os.IsNotExist(err) && info.IsDir() + fmt.Println(path, "is a directory:", b) +} diff --git a/idioms/214_pad_string_on_the_right/214_pad_string_on_the_right.go b/idioms/214_pad_string_on_the_right/214_pad_string_on_the_right.go new file mode 100644 index 0000000..15983ca --- /dev/null +++ b/idioms/214_pad_string_on_the_right/214_pad_string_on_the_right.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "strings" + "unicode/utf8" +) + +func main() { + m := 3 + c := "-" + for _, s := range []string{ + "", + "a", + "ab", + "abc", + "abcd", + "é", + } { + if n := utf8.RuneCountInString(s); n < m { + s += strings.Repeat(c, m-n) + } + fmt.Println(s) + } +} diff --git a/idioms/215_pad_string_on_the_left/215_pad_string_on_the_left.go b/idioms/215_pad_string_on_the_left/215_pad_string_on_the_left.go new file mode 100644 index 0000000..9b18db6 --- /dev/null +++ b/idioms/215_pad_string_on_the_left/215_pad_string_on_the_left.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "strings" + "unicode/utf8" +) + +func main() { + m := 3 + c := "-" + for _, s := range []string{ + "", + "a", + "ab", + "abc", + "abcd", + "é", + } { + if n := utf8.RuneCountInString(s); n < m { + s = strings.Repeat(c, m-n) + s + } + fmt.Println(s) + } +} diff --git a/idioms/219_replace_multiple_spaces_with_single_space/219_replace_multiple_spaces_with_single_space.go b/idioms/219_replace_multiple_spaces_with_single_space/219_replace_multiple_spaces_with_single_space.go new file mode 100644 index 0000000..1e9ad07 --- /dev/null +++ b/idioms/219_replace_multiple_spaces_with_single_space/219_replace_multiple_spaces_with_single_space.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "regexp" +) + +// regexp created only once, and then reused +var whitespaces = regexp.MustCompile(`\s+`) + +func main() { + s := ` + one two + three + ` + + t := whitespaces.ReplaceAllString(s, " ") + + fmt.Printf("t=%q", t) +} diff --git a/idioms/220b_create_a_tuple_value/220b_create_a_tuple_value.go b/idioms/220b_create_a_tuple_value/220b_create_a_tuple_value.go new file mode 100644 index 0000000..03a20b9 --- /dev/null +++ b/idioms/220b_create_a_tuple_value/220b_create_a_tuple_value.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" +) + +func main() { + x, y, z := f() + + fmt.Println(x, y, z) +} + +func f() (float64, string, chan int) { + a, b, c := 2.5, "hello", make(chan int) + return a, b, c +} diff --git a/idioms/221_remove_all_non_digits_characters/221_remove_all_non_digits_characters.go b/idioms/221_remove_all_non_digits_characters/221_remove_all_non_digits_characters.go new file mode 100644 index 0000000..0d738a7 --- /dev/null +++ b/idioms/221_remove_all_non_digits_characters/221_remove_all_non_digits_characters.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "regexp" +) + +func main() { + s := `height="168px"` + + re := regexp.MustCompile("[^\\d]") + t := re.ReplaceAllLiteralString(s, "") + + fmt.Println(t) +} diff --git a/idioms/222_find_the_first_index_of_an_element_in_list/222_find_the_first_index_of_an_element_in_list.go b/idioms/222_find_the_first_index_of_an_element_in_list/222_find_the_first_index_of_an_element_in_list.go new file mode 100644 index 0000000..3de8420 --- /dev/null +++ b/idioms/222_find_the_first_index_of_an_element_in_list/222_find_the_first_index_of_an_element_in_list.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []string{"huey", "dewey", "louie"} + x := "dewey" + + i := -1 + for j, e := range items { + if e == x { + i = j + break + } + } + + fmt.Printf("Found %q at position %d in %q", x, i, items) +} diff --git a/idioms/223_for_else_loop/223_for_else_loop.go b/idioms/223_for_else_loop/223_for_else_loop.go new file mode 100644 index 0000000..989db41 --- /dev/null +++ b/idioms/223_for_else_loop/223_for_else_loop.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []string{"foo", "bar", "baz", "qux"} + + for _, item := range items { + if item == "baz" { + fmt.Println("found it") + goto forelse + } + } + { + fmt.Println("never found it") + } + forelse: +} diff --git a/idioms/225_declare_and_use_an_optional_argument/225_declare_and_use_an_optional_argument.go b/idioms/225_declare_and_use_an_optional_argument/225_declare_and_use_an_optional_argument.go new file mode 100644 index 0000000..4cdf692 --- /dev/null +++ b/idioms/225_declare_and_use_an_optional_argument/225_declare_and_use_an_optional_argument.go @@ -0,0 +1,14 @@ +package main + +func f(x ...int) { + if len(x) > 0 { + println("Present", x[0]) + } else { + println("Not present") + } +} + +func main() { + f() + f(1) +} diff --git a/idioms/226_delete_last_element_from_list/226_delete_last_element_from_list.go b/idioms/226_delete_last_element_from_list/226_delete_last_element_from_list.go new file mode 100644 index 0000000..d6e58ed --- /dev/null +++ b/idioms/226_delete_last_element_from_list/226_delete_last_element_from_list.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" +) + +func main() { + items := []string{"banana", "apple", "kiwi"} + fmt.Println(items) + + items = items[:len(items)-1] + fmt.Println(items) +} diff --git a/idioms/227_copy_list/227_copy_list.go b/idioms/227_copy_list/227_copy_list.go new file mode 100644 index 0000000..bf79e08 --- /dev/null +++ b/idioms/227_copy_list/227_copy_list.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" +) + +func main() { + type T string + x := []T{"Never", "gonna", "shower"} + + y := make([]T, len(x)) + copy(y, x) + + y[2] = "give" + y = append(y, "you", "up") + + fmt.Println(x) + fmt.Println(y) +} diff --git a/idioms/228a_copy_a_file/228a_copy_a_file.go b/idioms/228a_copy_a_file/228a_copy_a_file.go new file mode 100644 index 0000000..afdf984 --- /dev/null +++ b/idioms/228a_copy_a_file/228a_copy_a_file.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" + "os" +) + +func main() { + src, dst := "/tmp/file1", "/tmp/file2" + + err := copy(dst, src) + if err != nil { + log.Fatalln(err) + } + + stat, err := os.Stat(dst) + if err != nil { + log.Fatalln(err) + } + fmt.Println(dst, "exists, it has size", stat.Size(), "and mode", stat.Mode()) +} + +func copy(dst, src string) error { + data, err := ioutil.ReadFile(src) + if err != nil { + return err + } + stat, err := os.Stat(src) + if err != nil { + return err + } + return ioutil.WriteFile(dst, data, stat.Mode()) +} + +func init() { + data := []byte("Hello") + err := ioutil.WriteFile("/tmp/file1", data, 0644) + if err != nil { + log.Fatalln(err) + } +} diff --git a/idioms/228b_copy_a_file/228b_copy_a_file.go b/idioms/228b_copy_a_file/228b_copy_a_file.go new file mode 100644 index 0000000..f91a09a --- /dev/null +++ b/idioms/228b_copy_a_file/228b_copy_a_file.go @@ -0,0 +1,51 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" + "os" +) + +func main() { + src, dst := "/tmp/file1", "/tmp/file2" + + err := copy(dst, src) + if err != nil { + log.Fatalln(err) + } + + stat, err := os.Stat(dst) + if err != nil { + log.Fatalln(err) + } + fmt.Println(dst, "exists, it has size", stat.Size(), "and mode", stat.Mode()) +} + +func copy(dst, src string) error { + data, err := ioutil.ReadFile(src) + if err != nil { + return err + } + stat, err := os.Stat(src) + if err != nil { + return err + } + err = ioutil.WriteFile(dst, data, stat.Mode()) + if err != nil { + return err + } + return os.Chmod(dst, stat.Mode()) +} + +func init() { + data := []byte("Hello") + err := ioutil.WriteFile("/tmp/file1", data, 0777) + if err != nil { + log.Fatalln(err) + } + err = os.Chmod("/tmp/file1", 0777) + if err != nil { + log.Fatalln(err) + } +} diff --git a/idioms/228c_copy_a_file/228c_copy_a_file.go b/idioms/228c_copy_a_file/228c_copy_a_file.go new file mode 100644 index 0000000..ad56366 --- /dev/null +++ b/idioms/228c_copy_a_file/228c_copy_a_file.go @@ -0,0 +1,58 @@ +package main + +import ( + "fmt" + "io" + "io/ioutil" + "log" + "os" +) + +func main() { + src, dst := "/tmp/file1", "/tmp/file2" + + err := copy(dst, src) + if err != nil { + log.Fatalln(err) + } + + stat, err := os.Stat(dst) + if err != nil { + log.Fatalln(err) + } + fmt.Println(dst, "exists, it has size", stat.Size(), "and mode", stat.Mode()) +} + +func copy(dst, src string) error { + f, err := os.Open(src) + if err != nil { + return err + } + defer f.Close() + stat, err := f.Stat() + if err != nil { + return err + } + g, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode()) + if err != nil { + return err + } + defer g.Close() + _, err = io.Copy(g, f) + if err != nil { + return err + } + return os.Chmod(dst, stat.Mode()) +} + +func init() { + data := []byte("Hello") + err := ioutil.WriteFile("/tmp/file1", data, 0777) + if err != nil { + log.Fatalln(err) + } + err = os.Chmod("/tmp/file1", 0777) + if err != nil { + log.Fatalln(err) + } +} diff --git a/idioms/229_cancel_an_operation/229_cancel_an_operation.go b/idioms/229_cancel_an_operation/229_cancel_an_operation.go new file mode 100644 index 0000000..275bac9 --- /dev/null +++ b/idioms/229_cancel_an_operation/229_cancel_an_operation.go @@ -0,0 +1,27 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + ctx, cancel := context.WithCancel(context.Background()) + go p(ctx) + time.Sleep(3 * time.Second) + cancel() + time.Sleep(3 * time.Second) +} + +func p(ctx context.Context) { + for i := 0; i < 10; i++ { + select { + case <-ctx.Done(): + return + default: + fmt.Println(i) + time.Sleep(time.Second) + } + } +} \ No newline at end of file diff --git a/idioms/230_timeout/230_timeout.go b/idioms/230_timeout/230_timeout.go new file mode 100644 index 0000000..60345fe --- /dev/null +++ b/idioms/230_timeout/230_timeout.go @@ -0,0 +1,25 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + p(ctx) +} + +func p(ctx context.Context) { + for i := 0; i < 100; i++ { + select { + case <-ctx.Done(): + return + default: + fmt.Println(i) + time.Sleep(time.Second) + } + } +} \ No newline at end of file diff --git a/idioms/231_test_if_bytes_are_a_valid_utf_8_string/231_test_if_bytes_are_a_valid_utf_8_string.go b/idioms/231_test_if_bytes_are_a_valid_utf_8_string/231_test_if_bytes_are_a_valid_utf_8_string.go new file mode 100644 index 0000000..fa9f583 --- /dev/null +++ b/idioms/231_test_if_bytes_are_a_valid_utf_8_string/231_test_if_bytes_are_a_valid_utf_8_string.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "unicode/utf8" +) + +func main() { + { + s := []byte("Hello, 世界") + b := utf8.Valid(s) + fmt.Println(b) + } + { + s := []byte{0xff, 0xfe, 0xfd} + b := utf8.Valid(s) + fmt.Println(b) + } +} diff --git a/idioms/232_read_a_command_line_boolean_flag/232_read_a_command_line_boolean_flag.go b/idioms/232_read_a_command_line_boolean_flag/232_read_a_command_line_boolean_flag.go new file mode 100644 index 0000000..25508d0 --- /dev/null +++ b/idioms/232_read_a_command_line_boolean_flag/232_read_a_command_line_boolean_flag.go @@ -0,0 +1,22 @@ +package main + +import ( + "flag" + "fmt" +) + +var verbose = flag.Bool("v", false, "verbose") + +func main() { + flag.Parse() + fmt.Println("verbose is", *verbose) +} + +// You can't pass a flag value in the Playground. +// Save the source as readflag.go on your computer and try it: +// go run readflag.go +// go run readflag.go -v +// go run readflag.go -v=1 +// go run readflag.go -v=true +// go run readflag.go -v=0 +// go run readflag.go -v=false \ No newline at end of file diff --git a/idioms/233_read_a_command_line_string_flag/233_read_a_command_line_string_flag.go b/idioms/233_read_a_command_line_string_flag/233_read_a_command_line_string_flag.go new file mode 100644 index 0000000..a4ee761 --- /dev/null +++ b/idioms/233_read_a_command_line_string_flag/233_read_a_command_line_string_flag.go @@ -0,0 +1,19 @@ +package main + +import ( + "flag" + "fmt" +) + +var country = flag.String("country", "Canada", "user home country") + +func main() { + flag.Parse() + fmt.Println("country is", *country) +} + +// You can't pass a flag value in the Playground. +// Save the source as readflag.go on your computer and try it: +// go run readflag.go +// go run readflag.go -v=France +// go run readflag.go -v France diff --git a/idioms/234_encode_bytes_to_base64/234_encode_bytes_to_base64.go b/idioms/234_encode_bytes_to_base64/234_encode_bytes_to_base64.go new file mode 100644 index 0000000..630694b --- /dev/null +++ b/idioms/234_encode_bytes_to_base64/234_encode_bytes_to_base64.go @@ -0,0 +1,12 @@ +package main + +import ( + "encoding/base64" + "fmt" +) + +func main() { + data := []byte("Hello world") + s := base64.StdEncoding.EncodeToString(data) + fmt.Println(s) +} diff --git a/idioms/235_decode_base64/235_decode_base64.go b/idioms/235_decode_base64/235_decode_base64.go new file mode 100644 index 0000000..933148b --- /dev/null +++ b/idioms/235_decode_base64/235_decode_base64.go @@ -0,0 +1,18 @@ +package main + +import ( + "encoding/base64" + "fmt" +) + +func main() { + str := "SGVsbG8gd29ybGQ=" + + data, err := base64.StdEncoding.DecodeString(str) + if err != nil { + fmt.Println("error:", err) + return + } + + fmt.Printf("%q\n", data) +} diff --git a/idioms/236c_large_quotient/236c_large_quotient.go b/idioms/236c_large_quotient/236c_large_quotient.go new file mode 100644 index 0000000..1b64456 --- /dev/null +++ b/idioms/236c_large_quotient/236c_large_quotient.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + var a int64 = 12345678 + var b int64 = 98765432109876 + + q := big.NewRat(a, b) + + fmt.Println(q) +} diff --git a/idioms/237a_xor_integers/237a_xor_integers.go b/idioms/237a_xor_integers/237a_xor_integers.go new file mode 100644 index 0000000..551320b --- /dev/null +++ b/idioms/237a_xor_integers/237a_xor_integers.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" +) + +func main() { + a, b := 230, 42 + c := a ^ b + + fmt.Printf("a is %12b\n", a) + fmt.Printf("b is %12b\n", b) + fmt.Printf("c is %12b\n", c) + fmt.Println("c ==", c) +} diff --git a/idioms/238a_xor_byte_arrays/238a_xor_byte_arrays.go b/idioms/238a_xor_byte_arrays/238a_xor_byte_arrays.go new file mode 100644 index 0000000..2628dc2 --- /dev/null +++ b/idioms/238a_xor_byte_arrays/238a_xor_byte_arrays.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" +) + +func main() { + a, b := []byte("Hello"), []byte("world") + + c := make([]byte, len(a)) + for i := range a { + c[i] = a[i] ^ b[i] + } + + fmt.Printf("a is %08b\n", a) + fmt.Printf("b is %08b\n", b) + fmt.Printf("c is %08b\n", c) + fmt.Println("c ==", c) + fmt.Printf("c as string would be %q\n", string(c)) +} diff --git a/idioms/239_find_first_regular_expression_match/239_find_first_regular_expression_match.go b/idioms/239_find_first_regular_expression_match/239_find_first_regular_expression_match.go new file mode 100644 index 0000000..e2cc475 --- /dev/null +++ b/idioms/239_find_first_regular_expression_match/239_find_first_regular_expression_match.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "regexp" +) + +func main() { + re := regexp.MustCompile(`\b\d\d\d\b`) + for _, s := range []string{ + "", + "12", + "123", + "1234", + "I have 12 goats, 3988 otters, 224 shrimps and 456 giraffes", + "See p.456, for word boundaries", + } { + x := re.FindString(s) + fmt.Printf("%q -> %q\n", s, x) + } +} diff --git a/idioms/241_yield_priority_to_other_threads/241_yield_priority_to_other_threads.go b/idioms/241_yield_priority_to_other_threads/241_yield_priority_to_other_threads.go new file mode 100644 index 0000000..529c993 --- /dev/null +++ b/idioms/241_yield_priority_to_other_threads/241_yield_priority_to_other_threads.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "runtime" + "time" +) + +func main() { + go fmt.Println("aaa") + go fmt.Println("bbb") + go fmt.Println("ccc") + go fmt.Println("ddd") + go fmt.Println("eee") + + runtime.Gosched() + busywork() + + time.Sleep(100 * time.Millisecond) +} + +func busywork() { + fmt.Println("main") +} \ No newline at end of file diff --git a/idioms/243_print_list/243_print_list.go b/idioms/243_print_list/243_print_list.go new file mode 100644 index 0000000..083fd02 --- /dev/null +++ b/idioms/243_print_list/243_print_list.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" +) + +func main() { + { + a := []int{11, 22, 33} + fmt.Println(a) + } + + { + a := []string{"aa", "bb"} + fmt.Println(a) + } + + { + type Person struct { + First string + Last string + } + x := Person{ + First: "Jane", + Last: "Doe", + } + y := Person{ + First: "John", + Last: "Doe", + } + a := []Person{x, y} + fmt.Println(a) + } + + { + x, y := 11, 22 + a := []*int{&x, &y} + fmt.Println(a) + } +} \ No newline at end of file diff --git a/idioms/244a_print_map/244a_print_map.go b/idioms/244a_print_map/244a_print_map.go new file mode 100644 index 0000000..d945b9a --- /dev/null +++ b/idioms/244a_print_map/244a_print_map.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" +) + +func main() { + { + m := map[string]int{ + "eleven": 11, + "twenty-two": 22, + } + fmt.Println(m) + } + + { + x, y := 7, 8 + m := map[string]*int{ + "seven": &x, + "eight": &y, + } + fmt.Println(m) + } +} diff --git a/idioms/244b_print_map/244b_print_map.go b/idioms/244b_print_map/244b_print_map.go new file mode 100644 index 0000000..02e1faf --- /dev/null +++ b/idioms/244b_print_map/244b_print_map.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + m := map[string]string{ + "eleven": "onze", + "twenty-two": "vingt-deux", + } + + fmt.Printf("%q", m) +} diff --git a/idioms/245_print_value_of_custom_type/245_print_value_of_custom_type.go b/idioms/245_print_value_of_custom_type/245_print_value_of_custom_type.go new file mode 100644 index 0000000..2a5cca8 --- /dev/null +++ b/idioms/245_print_value_of_custom_type/245_print_value_of_custom_type.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" +) + +// T represents a tank. It doesn't implement fmt.Stringer. +type T struct { + name string + weight int + firePower int +} + +// Person implement fmt.Stringer. +type Person struct { + FirstName string + LastName string + YearOfBirth int +} + +func (p Person) String() string { + return fmt.Sprintf("%s %s, born %d", p.FirstName, p.LastName, p.YearOfBirth) +} + +func main() { + { + x := T{ + name: "myTank", + weight: 100, + firePower: 90, + } + + fmt.Println(x) + } + { + x := Person{ + FirstName: "John", + LastName: "Doe", + YearOfBirth: 1958, + } + + fmt.Println(x) + } +} \ No newline at end of file diff --git a/idioms/246_count_distinct_elements/246_count_distinct_elements.go b/idioms/246_count_distinct_elements/246_count_distinct_elements.go new file mode 100644 index 0000000..d93731c --- /dev/null +++ b/idioms/246_count_distinct_elements/246_count_distinct_elements.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" +) + +func main() { + type T string + items := []T{"a", "b", "b", "aaa", "c", "a", "d"} + fmt.Println("items has", len(items), "elements") + + distinct := make(map[T]bool) + for _, v := range items { + distinct[v] = true + } + c := len(distinct) + + fmt.Println("items has", c, "distinct elements") +} diff --git a/idioms/249_declare_and_assign_multiple_variables/249_declare_and_assign_multiple_variables.go b/idioms/249_declare_and_assign_multiple_variables/249_declare_and_assign_multiple_variables.go new file mode 100644 index 0000000..70b0224 --- /dev/null +++ b/idioms/249_declare_and_assign_multiple_variables/249_declare_and_assign_multiple_variables.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + // a, b and c don't need to have the same type. + + a, b, c := 42, "hello", 5.0 + + fmt.Println(a, b, c) + fmt.Printf("%T %T %T \n", a, b, c) +} diff --git a/idioms/251_parse_binary_digits/251_parse_binary_digits.go b/idioms/251_parse_binary_digits/251_parse_binary_digits.go new file mode 100644 index 0000000..08714ec --- /dev/null +++ b/idioms/251_parse_binary_digits/251_parse_binary_digits.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "reflect" + "strconv" +) + +func main() { + s := "1101" + fmt.Println("s is", reflect.TypeOf(s), s) + + i, err := strconv.ParseInt(s, 2, 0) + if err != nil { + panic(err) + } + + fmt.Println("i is", reflect.TypeOf(i), i) +} diff --git a/idioms/252_conditional_assignment/252_conditional_assignment.go b/idioms/252_conditional_assignment/252_conditional_assignment.go new file mode 100644 index 0000000..1ce1cfc --- /dev/null +++ b/idioms/252_conditional_assignment/252_conditional_assignment.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" +) + +func main() { + var x string + if condition() { + x = "a" + } else { + x = "b" + } + + fmt.Println(x) +} + +func condition() bool { + return "Scorates" == "dog" +} diff --git a/idioms/253_print_stack_trace/253_print_stack_trace.go b/idioms/253_print_stack_trace/253_print_stack_trace.go new file mode 100644 index 0000000..73fb988 --- /dev/null +++ b/idioms/253_print_stack_trace/253_print_stack_trace.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "runtime/debug" +) + +func main() { + fmt.Println("Start") + myFancyFunc() + fmt.Println("The end.") +} + +func myFancyFunc() { + debug.PrintStack() +} diff --git a/idioms/254_replace_value_in_list/254_replace_value_in_list.go b/idioms/254_replace_value_in_list/254_replace_value_in_list.go new file mode 100644 index 0000000..0d126c0 --- /dev/null +++ b/idioms/254_replace_value_in_list/254_replace_value_in_list.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func main() { + x := []string{ + "a", + "", + "foo", + "bar", + "foo", + } + fmt.Printf("Before:\t x is %q\n", x) + + for i, s := range x { + if s == "foo" { + x[i] = "bar" + } + } + + fmt.Printf("After:\t x is %q\n", x) +} diff --git a/idioms/256_count_backwards/256_count_backwards.go b/idioms/256_count_backwards/256_count_backwards.go new file mode 100644 index 0000000..829b3c1 --- /dev/null +++ b/idioms/256_count_backwards/256_count_backwards.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" +) + +func main() { + for i := 5; i >= 0; i-- { + fmt.Println(i) + } +} diff --git a/idioms/257_traverse_list_backwards/257_traverse_list_backwards.go b/idioms/257_traverse_list_backwards/257_traverse_list_backwards.go new file mode 100644 index 0000000..1b526d6 --- /dev/null +++ b/idioms/257_traverse_list_backwards/257_traverse_list_backwards.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func main() { + items := []string{ + "oranges", + "apples", + "bananas", + } + + for i := len(items) - 1; i >= 0; i-- { + x := items[i] + fmt.Printf("Item %d = %v \n", i, x) + } +} diff --git a/idioms/258_convert_list_of_strings_to_list_of_integers/258_convert_list_of_strings_to_list_of_integers.go b/idioms/258_convert_list_of_strings_to_list_of_integers/258_convert_list_of_strings_to_list_of_integers.go new file mode 100644 index 0000000..59e684e --- /dev/null +++ b/idioms/258_convert_list_of_strings_to_list_of_integers/258_convert_list_of_strings_to_list_of_integers.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + "strconv" +) + +func main() { + a := []string{"11", "22", "33"} + + b := make([]int, len(a)) + var err error + for i, s := range a { + b[i], err = strconv.Atoi(s) + if err != nil { + panic(err) + } + } + + fmt.Println(b) +} diff --git a/idioms/259_split_on_several_separators/259_split_on_several_separators.go b/idioms/259_split_on_several_separators/259_split_on_several_separators.go new file mode 100644 index 0000000..9b6526a --- /dev/null +++ b/idioms/259_split_on_several_separators/259_split_on_several_separators.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "regexp" +) + +func main() { + s := "2021-03-11,linux_amd64" + + re := regexp.MustCompile("[,\\-_]") + parts := re.Split(s, -1) + + fmt.Printf("%q", parts) +} \ No newline at end of file diff --git a/idioms/260_create_an_empty_list_of_strings/260_create_an_empty_list_of_strings.go b/idioms/260_create_an_empty_list_of_strings/260_create_an_empty_list_of_strings.go new file mode 100644 index 0000000..565538d --- /dev/null +++ b/idioms/260_create_an_empty_list_of_strings/260_create_an_empty_list_of_strings.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" +) + +func main() { + var items []string + + fmt.Println("items has", len(items), "elements") + fmt.Printf("items is %q\n", items) + + items = append(items, "foobar") + + fmt.Println("items has", len(items), "elements") + fmt.Printf("items is %q\n", items) +} diff --git a/idioms/261_format_time_hours_minutes_seconds/261_format_time_hours_minutes_seconds.go b/idioms/261_format_time_hours_minutes_seconds/261_format_time_hours_minutes_seconds.go new file mode 100644 index 0000000..eb7fc4e --- /dev/null +++ b/idioms/261_format_time_hours_minutes_seconds/261_format_time_hours_minutes_seconds.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + d := time.Now() + x := d.Format("15:04:05") + fmt.Println(x) + + // The output may be "23:00:00" because the Playground's clock is fixed in the past. +} diff --git a/idioms/262_count_trailing_zero_bits/262_count_trailing_zero_bits.go b/idioms/262_count_trailing_zero_bits/262_count_trailing_zero_bits.go new file mode 100644 index 0000000..30ff89e --- /dev/null +++ b/idioms/262_count_trailing_zero_bits/262_count_trailing_zero_bits.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "math/bits" +) + +func main() { + var n uint = 112 + + t := bits.TrailingZeros(n) + + fmt.Println(t) +} diff --git a/idioms/266_repeated_string/266_repeated_string.go b/idioms/266_repeated_string/266_repeated_string.go new file mode 100644 index 0000000..1656275 --- /dev/null +++ b/idioms/266_repeated_string/266_repeated_string.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + v := "abc" + n := 5 + + s := strings.Repeat(v, n) + + fmt.Println(s) +} diff --git a/idioms/267_pass_string_to_argument_that_can_be_of_any_type/267_pass_string_to_argument_that_can_be_of_any_type.go b/idioms/267_pass_string_to_argument_that_can_be_of_any_type/267_pass_string_to_argument_that_can_be_of_any_type.go new file mode 100644 index 0000000..1818a09 --- /dev/null +++ b/idioms/267_pass_string_to_argument_that_can_be_of_any_type/267_pass_string_to_argument_that_can_be_of_any_type.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +func foo(x interface{}) { + if s, ok := x.(string); ok { + fmt.Println(s) + } else { + fmt.Println("Nothing.") + } +} + +func main() { + foo("Hello, world!") + foo(42) +} diff --git a/idioms/273_check_if_folder_is_empty/273_check_if_folder_is_empty.go b/idioms/273_check_if_folder_is_empty/273_check_if_folder_is_empty.go new file mode 100644 index 0000000..922d5da --- /dev/null +++ b/idioms/273_check_if_folder_is_empty/273_check_if_folder_is_empty.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "io" + "io/ioutil" + "os" +) + +func main() { + { + p := "/usr" + + dir, err := os.Open(p) + if err != nil { + panic(err) + } + defer dir.Close() + _, err = dir.Readdirnames(1) + b := err == io.EOF + fmt.Println(p, "is empty:", b) + } + { + p := "/tmp" + + dir, err := os.Open(p) + if err != nil { + panic(err) + } + defer dir.Close() + _, err = dir.Readdirnames(1) + b := err == io.EOF + fmt.Println(p, "is empty:", b) + } + { + p, err := ioutil.TempDir("", "") + if err != nil { + panic(err) + } + + dir, err := os.Open(p) + if err != nil { + panic(err) + } + defer dir.Close() + _, err = dir.Readdirnames(1) + b := err == io.EOF + fmt.Println(p, "is empty:", b) + } + { + p := "/tmp" + + dir, err := os.Open(p) + if err != nil { + panic(err) + } + defer dir.Close() + _, err = dir.Readdirnames(1) + b := err == io.EOF + fmt.Println(p, "is empty:", b) + } +} diff --git a/idioms/274_remove_all_white_space_characters/274_remove_all_white_space_characters.go b/idioms/274_remove_all_white_space_characters/274_remove_all_white_space_characters.go new file mode 100644 index 0000000..4df121b --- /dev/null +++ b/idioms/274_remove_all_white_space_characters/274_remove_all_white_space_characters.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "strings" + "unicode" +) + +const s = ` + a string full of +white space + ` + +func main() { + + t := strings.Map(func(r rune) rune { + if unicode.IsSpace(r) { + // if the character is a space, drop it + return -1 + } + // else keep it in the string + return r + }, s) + + fmt.Printf("t=%q", t) +} diff --git a/idioms/275_binary_digits_to_byte_array/275_binary_digits_to_byte_array.go b/idioms/275_binary_digits_to_byte_array/275_binary_digits_to_byte_array.go new file mode 100644 index 0000000..2277313 --- /dev/null +++ b/idioms/275_binary_digits_to_byte_array/275_binary_digits_to_byte_array.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "log" + "strconv" +) + +func main() { + s := "101010100000000011111111" + + if len(s)%8 != 0 { + log.Fatalf("Length %d is not a multiple of 8: %q", len(s), s) + } + + n := len(s) / 8 + a := make([]byte, n) + for i := range a { + b, err := strconv.ParseInt(s[i*8:i*8+8], 2, 0) + if err != nil { + log.Fatal(err) + } + a[i] = byte(b) + } + + fmt.Println(a) + fmt.Printf("%X", a) +} \ No newline at end of file diff --git a/idioms/278_read_one_line_from_the_standard_input/278_read_one_line_from_the_standard_input.go b/idioms/278_read_one_line_from_the_standard_input/278_read_one_line_from_the_standard_input.go new file mode 100644 index 0000000..a11392d --- /dev/null +++ b/idioms/278_read_one_line_from_the_standard_input/278_read_one_line_from_the_standard_input.go @@ -0,0 +1,33 @@ +package main + +import ( + "bufio" + "fmt" + "io/ioutil" + "log" + "os" +) + +func main() { + s := bufio.NewScanner(os.Stdin) + if ok := s.Scan(); !ok { + log.Fatal(s.Err()) + } + line := s.Text() + + fmt.Printf("Read line: %q\n", line) +} + +func init() { + // Simulate Stdin be replacing it with a given *File + err := ioutil.WriteFile("/tmp/stdin", []byte(`abc + 22 +foo bar `), 0644) + if err != nil { + panic(err) + } + os.Stdin, err = os.Open("/tmp/stdin") + if err != nil { + panic(err) + } +} \ No newline at end of file diff --git a/idioms/279_read_list_of_strings_from_the_standard_input/279_read_list_of_strings_from_the_standard_input.go b/idioms/279_read_list_of_strings_from_the_standard_input/279_read_list_of_strings_from_the_standard_input.go new file mode 100644 index 0000000..2b73084 --- /dev/null +++ b/idioms/279_read_list_of_strings_from_the_standard_input/279_read_list_of_strings_from_the_standard_input.go @@ -0,0 +1,38 @@ +package main + +import ( + "bufio" + "fmt" + "io/ioutil" + "log" + "os" +) + +func main() { + var lines []string + s := bufio.NewScanner(os.Stdin) + for s.Scan() { + line := s.Text() + lines = append(lines, line) + } + if err := s.Err(); err != nil { + log.Fatal(err) + } + fmt.Printf("Read %d lines\n", len(lines)) + fmt.Printf("%q", lines) +} + +func init() { + // Simulate Stdin be replacing it with a given *File + data := `abc + 22 +foo bar ` + err := ioutil.WriteFile("/tmp/stdin", []byte(data), 0644) + if err != nil { + panic(err) + } + os.Stdin, err = os.Open("/tmp/stdin") + if err != nil { + panic(err) + } +} diff --git a/idioms/280_filter_map/280_filter_map.go b/idioms/280_filter_map/280_filter_map.go new file mode 100644 index 0000000..fa69b24 --- /dev/null +++ b/idioms/280_filter_map/280_filter_map.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + x := map[string]string{ + "key1": "a", + "key2": "Othello", + "key3": "", + "key4": "nicolas", + "key5": "Bart", + } + + p := func(s string) bool { + // Return true if s is Capitalized, i.e. if its first character is uppercase. + if s == "" { + return false + } + c := s[:1] + return c == strings.ToUpper(c) + } + + fmt.Printf("Before:\t x is %q\n\n", x) + + for k, v := range x { + if !p(v) { + delete(x, k) + } + } + + fmt.Printf("After:\t x is %q\n\n", x) +} diff --git a/idioms/282_use_a_custom_type_as_map_key/282_use_a_custom_type_as_map_key.go b/idioms/282_use_a_custom_type_as_map_key/282_use_a_custom_type_as_map_key.go new file mode 100644 index 0000000..738d7e8 --- /dev/null +++ b/idioms/282_use_a_custom_type_as_map_key/282_use_a_custom_type_as_map_key.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func main() { + type Foo struct { + name string + x, y int + } + + m := make(map[Foo]string) + foo := Foo{name: "John", x: 42, y: 5} + m[foo] = "Professor" + + fmt.Println(m) +} diff --git a/idioms/283_split_with_a_custom_string_separator/283_split_with_a_custom_string_separator.go b/idioms/283_split_with_a_custom_string_separator/283_split_with_a_custom_string_separator.go new file mode 100644 index 0000000..8e88bdf --- /dev/null +++ b/idioms/283_split_with_a_custom_string_separator/283_split_with_a_custom_string_separator.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "Love is all is alright" + sep := " is " + + parts := strings.Split(s, sep) + + fmt.Println(len(parts)) + fmt.Println(parts) +} diff --git a/idioms/284_created_a_zeroed_list_of_integers/284_created_a_zeroed_list_of_integers.go b/idioms/284_created_a_zeroed_list_of_integers/284_created_a_zeroed_list_of_integers.go new file mode 100644 index 0000000..5560a31 --- /dev/null +++ b/idioms/284_created_a_zeroed_list_of_integers/284_created_a_zeroed_list_of_integers.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func main() { + n := 8 + + a := make([]int, n) + + fmt.Println(a) +} diff --git a/idioms/286_iterate_over_characters_of_a_string/286_iterate_over_characters_of_a_string.go b/idioms/286_iterate_over_characters_of_a_string/286_iterate_over_characters_of_a_string.go new file mode 100644 index 0000000..ebab7f7 --- /dev/null +++ b/idioms/286_iterate_over_characters_of_a_string/286_iterate_over_characters_of_a_string.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +func main() { + s := "Résumé" + + i := 0 + for _, c := range s { + fmt.Printf("Char %d is %c\n", i, c) + i++ + } +} diff --git a/idioms/287_number_of_bytes_of_a_string/287_number_of_bytes_of_a_string.go b/idioms/287_number_of_bytes_of_a_string/287_number_of_bytes_of_a_string.go new file mode 100644 index 0000000..3eb2b62 --- /dev/null +++ b/idioms/287_number_of_bytes_of_a_string/287_number_of_bytes_of_a_string.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func main() { + s := "Résumé" + + n := len(s) + + fmt.Printf("%q has %d bytes", s, n) +} diff --git a/idioms/289_concatenate_two_strings/289_concatenate_two_strings.go b/idioms/289_concatenate_two_strings/289_concatenate_two_strings.go new file mode 100644 index 0000000..8f5646a --- /dev/null +++ b/idioms/289_concatenate_two_strings/289_concatenate_two_strings.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +func main() { + a, b := "Hello", " Universe" + + s := a + b + + fmt.Printf("a is %q\n", a) + fmt.Printf("b is %q\n", b) + fmt.Printf("s is %q\n", s) +} diff --git a/idioms/290_sort_sublist/290_sort_sublist.go b/idioms/290_sort_sublist/290_sort_sublist.go new file mode 100644 index 0000000..2c67f4d --- /dev/null +++ b/idioms/290_sort_sublist/290_sort_sublist.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "sort" +) + +type Item struct { + label string +} + +// c returns true if x is "inferior to" y (in a custom way) +func c(x, y Item) bool { + return x.label < y.label +} + +func main() { + items := []Item{ + {"start"}, + {"ccc"}, + {"aaa"}, + {"ddd"}, + {"bbb"}, + {"end"}, + } + fmt.Println("Unsorted:", items) + + // Sort the slice, except the first and the last elements + i, j := 1, len(items)-1 + sub := items[i:j] + sort.Slice(sub, func(a, b int) bool { + return c(sub[a], sub[b]) + }) + fmt.Println("Sorted: ", items) +} diff --git a/idioms/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8.go b/idioms/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8.go new file mode 100644 index 0000000..1a12d4a --- /dev/null +++ b/idioms/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8/292_write_ni_hao_in_chinese_to_standard_output_in_utf_8.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("Hello World and 你好") +}